﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.Office.Tools.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
//线程用到命名空间
using System.Threading;
using System.Data.OleDb;



namespace 料单生成
{
    public partial class Sheet2
    {
        private void Sheet2_Startup(object sender, System.EventArgs e)
        {
        }

        private void Sheet2_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO 设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InternalStartup()
        {
            this.button1.Click += new System.EventHandler(this.button1_Click);
            this.button2.Click += new System.EventHandler(this.button2_Click);
            this.buttonAdvancedStatus.Click += new System.EventHandler(this.buttonAdvancedStatus_Click);
            this.button3.Click += new System.EventHandler(this.button3_Click);
            this.button4.Click += new System.EventHandler(this.button4_Click);
            this.button5.Click += new System.EventHandler(this.button5_Click);
            this.buttonPCBOUT.Click += new System.EventHandler(this.button6_Click);
            this.button7.Click += new System.EventHandler(this.button7_Click);
            this.buttonALLPCPOUT.Click += new System.EventHandler(this.buttonALLPCPOUT_Click);
            this.button8.Click += new System.EventHandler(this.button8_Click);
            this.button9.Click += new System.EventHandler(this.button9_Click);
            this.button10.Click += new System.EventHandler(this.button10_Click);
            this.button11.Click += new System.EventHandler(this.button11_Click);
            this.button12.Click += new System.EventHandler(this.button12_Click);
            this.ExprotReplace.Click += new System.EventHandler(this.ExprotReplace_Click);
            this.ComSheets.MouseDown += new System.Windows.Forms.MouseEventHandler(this.ComSheets_MouseDown);
            this.button13.Click += new System.EventHandler(this.button13_Click);
            this.button14.Click += new System.EventHandler(this.button14_Click);
            this.button15.Click += new System.EventHandler(this.button15_Click);
            this.button16.Click += new System.EventHandler(this.button16_Click);
            this.button17.Click += new System.EventHandler(this.button17_Click);
            this.button18.Click += new System.EventHandler(this.button18_Click);
            this.button19.Click += new System.EventHandler(this.button19_Click);
            this.button20.Click += new System.EventHandler(this.button20_Click);
            this.button21.Click += new System.EventHandler(this.button21_Click);
            this.button22.Click += new System.EventHandler(this.button22_Click);
            this.button23.Click += new System.EventHandler(this.button23_Click);
            this.button24.Click += new System.EventHandler(this.button24_Click);
            this.button25.Click += new System.EventHandler(this.button25_Click);
            this.button26.Click += new System.EventHandler(this.button26_Click);
            this.button27.Click += new System.EventHandler(this.button27_Click);
            this.button28.Click += new System.EventHandler(this.button28_Click);
            this.button30.Click += new System.EventHandler(this.button30_Click);
            this.button31.Click += new System.EventHandler(this.button31_Click);
            this.button32.Click += new System.EventHandler(this.button32_Click);
            this.comboBox5.MouseDown += new System.Windows.Forms.MouseEventHandler(this.comboBox5_MouseDown);
            this.RESSTORPRO.Click += new System.EventHandler(this.RESSTORPRO_Click);
            this.button33.Click += new System.EventHandler(this.button33_Click);
            this.Startup += new System.EventHandler(this.Sheet2_Startup);
            this.Shutdown += new System.EventHandler(this.Sheet2_Shutdown);

        }

        #endregion


     
        //------------------全局变量说明------------------------------------
        
        //存储在库中没查找到的内容
        List<string> FindList = new List<string>();     
        int ProCount=0;


        //读取器件库内容到Lib_List中  LibFlag 为0说明已经读取过了
        List<string> Lib_List = new List<string>();     //存储读取的所有内容
        bool LibFlag = true;                            //读取库文件标志

        //存储总表所有元件的未整理时的内容（即合并完成后自动存入到这里）
        List<string> OkAllList = new List<string>();


        //存储总表所有元件的未整理时的内容（即合并完成后自动存入到这里）
        List<string> OkSingleAllList = new List<string>();

        //存储所有排序表内容
        List<string> GAllSortList = new List<string>();
        bool GSortflag = false;



        //打开多个BOM的全局变量
        string[] BomFilePath = new string[100];                  //存放打个BOM时的路径
        string[] BomFileName = new string[100];                  //存放打个BOM时的文件名
        int BomNumCount = 0;                                    //存打开多个BOM时的个数
        //打开多个BOM的全局变量结束

        //复制所有副本的计数器
        int PcbOldCopyCount = 1;
        bool PcbOutFlag = true;

        //string[] PartClass = new string[]{ "贴片电阻", "贴片电容", "贴片电感","贴片磁珠","贴片共模电感","自恢复保险", "集成电路", "电源模块", "晶体振荡器", "贴片晶体", "贴片二极管", "贴片稳压二极管", "贴片钽电容","继电器","精密贴片电阻", "贴片铝电解", "功率贴片电感", "插件电解电容", "插件金属膜电阻", "高压电解电容", "Y1安规电容", "Y2安规电容", "X2安规电容", "X2安规电容", "压敏电阻", "插件二极管", "贴片整流硅桥", "插件小圆柱型晶体", "插件整流硅桥", "插件精密金属膜电阻", "贴片红色发光二极管", "贴片绿色发光二极管", "插件红色3mm发光二极管", "插件绿色3mm发光二极管", "插件红色4mm发光二极管", "插件绿色5mm发光二极管", "立式侧调电位器", "立式顶调电位器", "卧式顶调电位器", "卧式侧调电位器", "SIM卡座", "抽屉式SIM卡座", "GPS模块", "GPRS模块", "WIFI模块", "电源滤波器", "变压器","锂电池","锂电池座","(快断)5x20mm玻璃保险","(慢断)5x20mm玻璃保险","轻触开关","贴片微型拨码开关","DB9孔型母座","DB9针型公座","1.27双排排母","1.27双排排针","2.54白色针型插座","中型插座","万可端子","TVS放电管","半导体放电管","陶瓷放电管(GDT)"};
        string[] PartClass = new string[] { "贴片电阻", "贴片电容", "贴片电感", "贴片磁珠", "贴片共模电感", "自恢复保险", "集成电路", "电源模块", "晶体振荡器", "贴片晶体", "贴片二极管", "贴片稳压二极管", "贴片钽电容", "精密贴片电阻", "贴片铝电解", "Y1安规电容", "压敏电阻", "整流硅桥", "小圆柱型晶体", "金属膜电阻", "红色发光二极管", "红色3mm发光二极管", "电位器", "电源滤波器", "变压器", "(快断)5x20mm玻璃保险", "轻触开关", "贴片微型拨码开关", "DB9孔型母座", "2.54白色针型插座", "中型插座", "万可端子", "TVS放电管", "陶瓷放电管(GDT)" };

        //bool updateflag = true;
        int rowcount = 0;

        string[] DelBom = new string[8] { "程序", "器件库", "PCB输出样板", "多表配置样板", "总表封面样板", "总表样板", "料单样板", "更改记录样板" };
        //string[] delbom = new string[5] { "","","","","","","",};
        string[] delbomname = new string[] { "总表样板", "料单样板", "总表封面样板", "更改记录样板", "PCB输出样板", "加工参数" };
       
        List<string> AllReplace_List = new List<string>();

        //读取器件库内家容到Lib_List中
        List<string> SingleBomList = new List<string>();     //存储读取的所有内容
        
        List<string> ReadRecList = new List<string>();     //存储读取的所有内容ReadRecList;

        //器件替换表路径
        static string ReplacePath = @"C:\BOM\Replace.txt";
        //料单配置路径
        static string ConfigPath = @"C:\BOM\OrderOutS.xml";
        //器件库路径
        static string AllLibPath = @"C:\BOM\AllLib.txt";

       //  字符串比较
        // 反回1为完全相同
        // 反回2为str2的内容包含str1，例如 str1= 电阻，str2= 贴片电阻，就是str2的内容包含str1
        // 反回3为错误

        public int stringcompare(string str1, string str2) 
        {           
            int s1, s2, dencount = 0;
            if (str1 == str2)
            {
                //MessageBox.Show("两个内容是相同的");
                return 1;
            }
            else
            {
                if (str1.Length < str2.Length)
                {
                    for (int i = 0; i < str1.Length; i++)
                    {
                        for (int j = 0; j < str2.Length; j++)
                        {
                            if (str1.Substring(i, 1) == str2.Substring(j, 1))
                            {
                                if (i == 0)//如是是全疲惫那么这个要等于0才可以
                                {
                                    s1 = i; s2 = j;
                                    s1++; s2++;
                                    if ((s1 < str1.Length) && (s2 < str2.Length))
                                    {

                                        while (str1.Substring(s1, 1) == str2.Substring(s2, 1))
                                        {

                                            if ((s1 < (str1.Length - 1)) && (s2 < (str2.Length - 1)))
                                            {
                                                s1++; s2++; dencount++;
                                            }
                                            else
                                            {
                                                return 2;
                                            }

                                        }
                                        return 3;
                                    }
                                }
                                else
                                {
                                    return 3;
                                }
                            }
                        }
                    }
                }
                return 3;
            }
        }

       //  PCB输出
        public void PcbOut()
        {
            // 表格的列进行配置

            //1  序号
            int SerialColumnConfig = 1;
            //2  项目名称
            //int  ProNameColumnConfig = 2;
            //3  打印日期
            //int PrintDateColumnConfig = 3;
            //4  BOM文件名	
            //int BomFileNameColumnConfig = 4;
            //5  BOM中文名
            //int BomChinaNameColumnConfig = 5;
            //6  PCB板名
            int PcbNameColumnConfig = 6;
            //7  PCB版本
            int PcbRevColumnConfig = 7;
            //8  PCB尺寸
            int PcbSizeColumnConfig = 8;
            //9  板内日期
            int PcbDateColumnConfig = 9;
            //10 板层	
            int PcbLayerColumnConfig = 10;
            //11 下单数量
            int PcbNumberColumnConfig = 11;
            //12 厚度
            int PcbThicknessColumnConfig = 12;
            //13 工艺	
            int PcbCraftColumnConfig = 13;
            //14 加工日期
            //int PcbOutDateColumnConfig = 14;
            //15 路径
            //int PcbPathColumnConfig = 15;
            //16 PCB软件版本
            int SoftRevColumnConfig = 16;
            //1  序号
            int SerialColumn = 1;
            //6  PCB板名
            int PcbNameColumn = 2;
            //7  PCB版本
            //int PcbRevColumn = 2;
            //8  PCB尺寸
            int PcbSizeColumn = 3;
            //9  板内日期
            int PcbDateColumn = 5;
            //11 下单数量
            int PcbNumberColumn = 6;
            //10 板层	
            int PcbLayerColumn = 7;
            //12 厚度
            int PcbThicknessColumn = 8;
            //16 备注： PCB软件版本
            int SoftRevColumn = 9;
            //13 工艺	
            //int PcbCraftColumn = 13;

            //2  项目名称
            //int ProNameColumn = 2;
            //3  打印日期
            //int PrintDateColumn = 3;
            //4  BOM文件名	
            //int BomFileNameColumn = 4;
            //5  BOM中文名
            //int BomChinaNameColumn = 5;
            //14 加工日期
            //int PcbOutDateColumn = 14;
            //15 路径
            //int PcbPathColumn = 15;

            ProStatus.Text = "正在处理,请稍后...";
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int PcbNum = 0,CopyTab=0,BomConfig=0;
            string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                tabname[i - 1] = workbook.Worksheets[i].Name;       //存工作簿
                if (workbook.Worksheets[i].Name == "PCB输出样板")
                {
                    PcbNum = i;
                }
                if (workbook.Worksheets[i].Name == ("PCB输出(" + TextBoxBomName.Text + ")"))
                {
                    CopyTab = i;
                }

                if (workbook.Worksheets[i].Name == "多表配置")
                {
                    BomConfig = i;
                }
                if (workbook.Worksheets[i].Name == "PCB输出(多表)")
                {
                    //PCB输出样板存副本
                    Excel.Worksheet dl = workbook.Worksheets[i];//要操作的表的索引。
                    dl.Name = "PCB输出(多表)副本" + PcbOldCopyCount; PcbOldCopyCount++;
                }
            }      
            //PCB输出样板存副本
            Excel.Worksheet PcbOutSheetCopy = workbook.Worksheets[PcbNum];//要操作的表的索引。
            //PCB输出多表配置
            Excel.Worksheet AllBomConfig = workbook.Worksheets[PcbNum];
            if (PcbOutFlag==false)
            { AllBomConfig = workbook.Worksheets[BomConfig]; }//要操作的表的索引。
            //复制一个表
            if (CopyTab != 0)
            {               
                Excel.Worksheet DeleteCopy = workbook.Worksheets[CopyTab];
                DeleteCopy.Name = "PCB输出(" + TextBoxBomName.Text + ")" + "副本" + PcbOldCopyCount; 
                PcbOldCopyCount++;
                //删除表，现在不这么做，现在是复制为副本
                //DeleteCopy.Delete();
                //CopyTab = 0;
            }
            object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            PcbOutSheetCopy.Copy(Missing, PcbOutSheetCopy);
            //对新建的PCB输出样板进行操作
            Excel.Worksheet PcbOutSheet = workbook.Worksheets[PcbNum + 1];//要操作的表的索引。
            if (PcbOutFlag)
            { PcbOutSheet.Name = "PCB输出(" + TextBoxBomName.Text + ")"; }
            else
            { PcbOutSheet.Name = "PCB输出(多表)";}
            //ProStatus.Text = string.Empty;
            //ProStatus.Text = "正在处理" + PcbOutSheet.Name + "表，请稍后...";

            string TempStr = "";
            Excel.Range range;
            if (PcbOutFlag)
	        {
                PcbOutSheet.Cells[4, 1] = "1";
                PcbOutSheet.Cells[4, 2] = textBoxPCB.Text;
                PcbOutSheet.Cells[4, 3] = textBoxSize.Text;
                PcbOutSheet.Cells[4, 4] = "新做";
                PcbOutSheet.Cells[4, 5] = PcbDate.Text;
                PcbOutSheet.Cells[4, 6] = textBoxPcbNum.Text;     // "10";
                PcbOutSheet.Cells[4, 7] = comboBoxLayer.Text;
                PcbOutSheet.Cells[4, 8] = comboBoxThickness.Text; //"1.6";
                //设置一下行高
                for (int i = 0; i < 24; i++)
                {
                    range = PcbOutSheet.Rows[5, this.missing];
                    range.Delete(Excel.XlDirection.xlDown);
                }
                range = PcbOutSheet.Rows[4, this.missing];
                range.RowHeight = "100";
	        }
            else
            {
                int idnum = 1 ;
                for (int PCBrow = 4; PCBrow < 50; PCBrow++)
                {
                    //读序号
                    range = AllBomConfig.Range[AllBomConfig.Cells[PCBrow - 2, SerialColumnConfig], AllBomConfig.Cells[PCBrow - 2, SerialColumnConfig]];                         //第1列内容为序号
                    TempStr = range.Text.ToString();

                    if (TempStr == "")
                    {
                        break;
                    }
                    //序号
                    PcbOutSheet.Cells[PCBrow, SerialColumn] = idnum; idnum++;
                    //PCB板名
                    range = AllBomConfig.Range[AllBomConfig.Cells[PCBrow - 2, PcbNameColumnConfig], AllBomConfig.Cells[PCBrow - 2, PcbNameColumnConfig]];                         //第1列内容为序号
                    TempStr = range.Text.ToString();
                    //PCB版本
                    range = AllBomConfig.Range[AllBomConfig.Cells[PCBrow - 2, PcbRevColumnConfig], AllBomConfig.Cells[PCBrow - 2, PcbRevColumnConfig]];                         //第1列内容为序号
                    TempStr = TempStr + range.Text.ToString();
                    PcbOutSheet.Cells[PCBrow, PcbNameColumn] = TempStr;
                    //PCB尺寸
                    range = AllBomConfig.Range[AllBomConfig.Cells[PCBrow - 2, PcbSizeColumnConfig], AllBomConfig.Cells[PCBrow - 2, PcbSizeColumnConfig]];                         //第1列内容为序号
                    TempStr = range.Text.ToString();
                    PcbOutSheet.Cells[PCBrow, PcbSizeColumn] = TempStr;
                    //板内日期
                    range = AllBomConfig.Range[AllBomConfig.Cells[PCBrow - 2, PcbDateColumnConfig], AllBomConfig.Cells[PCBrow - 2, PcbDateColumnConfig]];                         //第1列内容为序号
                    TempStr = range.Text.ToString();
                    PcbOutSheet.Cells[PCBrow, PcbDateColumn] = TempStr;
                    //下单数量
                    range = AllBomConfig.Range[AllBomConfig.Cells[PCBrow - 2, PcbNumberColumnConfig], AllBomConfig.Cells[PCBrow - 2, PcbNumberColumnConfig]];                         //第1列内容为序号
                    TempStr = range.Text.ToString();
                    PcbOutSheet.Cells[PCBrow, PcbNumberColumn] = TempStr;
                    //板层数
                    range = AllBomConfig.Range[AllBomConfig.Cells[PCBrow - 2, PcbLayerColumnConfig], AllBomConfig.Cells[PCBrow - 2, PcbLayerColumnConfig]];                         //第1列内容为序号
                    TempStr = range.Text.ToString();
                    PcbOutSheet.Cells[PCBrow, PcbLayerColumn] = TempStr;
                    //厚度
                    range = AllBomConfig.Range[AllBomConfig.Cells[PCBrow - 2, PcbThicknessColumnConfig], AllBomConfig.Cells[PCBrow - 2, PcbThicknessColumnConfig]];                         //第1列内容为序号
                    TempStr = range.Text.ToString();
                    PcbOutSheet.Cells[PCBrow, PcbThicknessColumn] = TempStr;
                    //软件版本
                    range = AllBomConfig.Range[AllBomConfig.Cells[PCBrow - 2, SoftRevColumnConfig], AllBomConfig.Cells[PCBrow - 2, SoftRevColumnConfig]];                         //第1列内容为序号
                    TempStr = range.Text.ToString();
                    //加工工艺
                    range = AllBomConfig.Range[AllBomConfig.Cells[PCBrow - 2, PcbCraftColumnConfig], AllBomConfig.Cells[PCBrow - 2, PcbCraftColumnConfig]];                         //第1列内容为序号
                    TempStr = TempStr +  range.Text.ToString();
                    PcbOutSheet.Cells[PCBrow, SoftRevColumn] = TempStr;

                }
            }

            ProStatus.Text = "PCB输出已处理已完成。";      
     }

       //单张表处理
        public void bomProExcel()
        {
            ProStatus.Text = "正在处理,请稍后...";
            int P_int_Count = 0;//记录正在读取的行数
            string P_str_Line, P_str_Content = "";//记录读取行的内容及遍历到的内容 

            int txttempcolumn = 0;            //当前行正处在那一列的位置
            int tempdesignatorcolumn = 0;    //protel99se存出时元件标号列开始的位置 列临时位置

            // int excelcolumn = 1;           //excel列号                
            //string[] tabheader = new string[9] { "序号", "统一编号", "器件名称", "规格型号", "封装", "数量", "编号", "加工数量", "备注" };
            int idnum = 1;                                      //存储当前操作行的序号1列，统一编号2列
            string partname = "", parttype = "", partfoot = ""; //存储当前操作行的器件名3列，器件规格4列，封装5列
            string exceldesignator = "";      //元件编号标识符7列，例如C1,C2,

            /*可配置excel单元格列的位置*/
            int txtpartname = 3;                 //器件的名称
            int txtparttypecolumn = 4;          //元件参数 列位置
            int txtfootprintcolumn = 5;         //元件封装列位置
            int txtusedcolumn = 6;              //元件用量 列位置
            int txtdesignatorcolumn = 7;        //元件标号 列位置
            int txtProductionNum = 8;           //生产数量 列位置
            //int txtlibrefcolumn=10;             //原里图名称

            // excel开始行号
            int excelrow = 3;                   //默认是从1开始，因为用板，1-2行不填，3行开始 excel启始行号  
       
            label1.Text = "";
            label2.Text = "";
            label3.Text = "";
            comboBox1.Items.Clear();
            comboBox1.Text = "";
            comboBox2.Items.Clear();
            comboBox2.Text = "";
            comboBox3.Items.Clear();
            comboBox3.Text = "";
            FindList.Clear();           
            ProCount = 0;
            if (LibFlag)//等于真没有加载过
            Lib_List.Clear();
            


            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int sheetnum = 0, PartLib = 0;
            string[] tabname = new string[100];   //workbook.Worksheets.Count存工作簿中所有表名 最多100个表
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                tabname[i - 1] = workbook.Worksheets[i].Name;       // + " "存工作簿
                if (workbook.Worksheets[i].Name == "料单样板")
                {
                    sheetnum = i;
                }
                if (workbook.Worksheets[i].Name == "器件库")
                {
                    PartLib = i;
                }
            }

            //ProStatus.BackColor = ;
            //器件库
            Excel.Worksheet PartLibSheet = workbook.Worksheets[PartLib];    //要操作的表的索引为器件库。
           // Excel.Range range;          

            //int Lib_Count = 0;                                                                                                          //存储字符的个数
            string TempStr = "";
            if (LibFlag)
            {
                //读取退出
                StreamReader ReplaceReader = new StreamReader(AllLibPath, Encoding.Default);  //实例化流读取对象
                while ((TempStr = ReplaceReader.ReadLine()) != null)                                           //循环读取文本文件中的每一行
                {
                    Lib_List.Add(TempStr.ToUpper());                                                                 //将读取到的行内容添加到泛型集合中
                }
                ReplaceReader.Close();
                ReplaceReader.Dispose();
                ////存储读取库中的内容
                ////把器件库中所有器件写入Lib_List进行处理
                //for (int TempRow = 1; TempRow < 10000; TempRow++)//遍历数据集中表的行数
                //{
                //    range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, 1], PartLibSheet.Cells[TempRow, 1]];                         //第1列内容为序号
                //    TempStr = range.Text.ToString();
                //    if (TempStr == (TempRow.ToString()))
                //    {
                //        for (int TempColumn = 1; TempColumn < 5; TempColumn++)                                                          //遍历数据集中表的列数
                //        {
                //            TempStr = "";
                //            range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, TempColumn], PartLibSheet.Cells[TempRow, TempColumn]];   //第2-4列内容为器件名称，规格型号，封装
                //            TempStr = range.Text.ToString();
                //            TempStr = TempStr.ToUpper(); //所有的转换为大写的内容
                //            Lib_List.Add(TempStr);//将读取到的行内容添加到泛型集合中
                //            Lib_Count++;//使当前读取行数加1
                //        }
                //    }
                //    else
                //    {
                //        break;
                //    }
                //}
                LibFlag = false; //读取完成标志已读
            }//读取结束           
            //MessageBox.Show("已经将\"器件库.xlsx\"工作表中的数据存到了一个字符串上。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);


           // WriterLibFile();

            /**************读取要转换的BOM文件到P_str_List中*********/
            List<string> P_str_List = new List<string>();   //存储读取的所有内容
            StreamReader SReader = new StreamReader(BomPath.Text, Encoding.Default);//实例化流读取对象
            while ((P_str_Line = SReader.ReadLine()) != null)       //循环读取文本文件中的每一行
            {
                P_str_Line = P_str_Line.ToUpper();                  //转换为大写字符
                P_str_List.Add(P_str_Line);                         //将读取到的行内容添加到泛型集合中
                P_int_Count++;                                      //使当前读取行数加1
            }


            //料单样板存副本
            Excel.Worksheet BomToExcelSheetCopy = workbook.Worksheets[sheetnum];//要操作的表的索引。
            //复制一个表
            object Missing = System.Reflection.Missing.Value;                   //获取缺少的object类型值
            BomToExcelSheetCopy.Copy(Missing, BomToExcelSheetCopy);

            //料单样板
            Excel.Worksheet BomToExcelSheet = workbook.Worksheets[sheetnum + 1];//要操作的表的索引。

            //有问题，是数组溢出 已改为100
            int t1 = 0, t2 = 0; ;
            for (int l = 1; l <= workbook.Worksheets.Count; l++)
            {
               // tabname[l - 1] = workbook.Worksheets[l].Name;       // + " "存工作簿
                if (workbook.Worksheets[l].Name == TextBoxBomName.Text)
                {
                    //MessageBox.Show("此表已转换过，是否复盖旧的");
                    t1 = 10;
                    t2 = l;
                }
            }

            ProStatus.Text = "正在处理" + TextBoxBomName.Text  + "表，请稍后。。。";

            if (t1 != 10)
            {
                BomToExcelSheet.Name = TextBoxBomName.Text;
            }
            else
            {
                BomToExcelSheet = workbook.Worksheets[t2];
                BomToExcelSheet.Name = TextBoxBomName.Text + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
                BomToExcelSheet = workbook.Worksheets[sheetnum + 1];
                BomToExcelSheet.Name = TextBoxBomName.Text;
            }            

            //ProStatus.Text = string.Empty;
            ProStatus.Text = "正在处理" + BomToExcelSheet.Name + "表，请稍后...";


            //string BomRev = textBoxBomRev.Text;   //料单的版本
            //string BomName = textBoxChinaName.Text; // "L1305主机板"; //BOM表转出后中文名  
            //自定义页眉
            BomToExcelSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
            BomToExcelSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18" + textBoxProduct.Text + textBoxChinaName.Text + "元件清单";
            BomToExcelSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" + comboBoxBomRev.Text;// textBoxBomRev.Text;
            //自定义页脚
            BomToExcelSheet.PageSetup.LeftFooter = @"&""微软雅黑,常规""日期:" + dateTimePicker1.Text;
            BomToExcelSheet.PageSetup.CenterFooter = @"&""微软雅黑,常规""第&P页/共&N页";
            BomToExcelSheet.PageSetup.RightFooter = "";


            //单板生产数量
            BomToExcelSheet.Cells[2, txtProductionNum] = textBoxPcbNum.Text;

            //分解表开始处理
            if ((BomPath.Text != "") && comboBoxSoftRev.Text == "protel99se")      //判断是否选择了文件
            {

                P_str_Content = P_str_List[3];//记录遍历到的值

                int TempD = 0, PartType = 0, Designator = 0, Footprint = 0;// Used = 0,
                for (int s = 0; s < P_str_Content.Length; s++)
                {
                    //Used = 0;
                    if (P_str_Content.Substring(s, 1) == " ")
                    {
                        if (TempD == 0) PartType = s + 1;
                        if (TempD == 1) Designator = s + 1;
                        if (TempD == 1) tempdesignatorcolumn = s + 1;
                        if (TempD == 2) Footprint = s + 1;
                        TempD++;
                    }
                }

                
                int TempLength = P_str_Content.Length;//黑认的字符长度

                while (P_str_Content.Substring(TempLength - 1, 1) == " ")//去除后面的空格字符
                {
                    TempLength--;
                }
                TempLength++;


                //分解BOM中内容到Excel中
                for (int i = 4; i < P_str_List.Count; i++)//遍历泛型集合  I为记事本，文本行号
                {
                    P_str_Content = P_str_List[i];//记录遍历到的值                    
                    //int[] China = new int[100];
                    int ChinaCount = 0;
                    if (P_str_Content.Length < TempLength)//小于这个值的话说明这一行内容有中文
                    {
                        for (int p = 0; p < P_str_Content.Length; p++)
			            {
                            char j = P_str_Content[p];
                            ushort s = j;
                            if (s>255)
                            {
                               ChinaCount++; 
                            }
                            //if (s >= 0x4E00 && s <= 0x9FA5)
                            //{
                            //    //  China[ChinaCount] = s;//中文
                            //    ChinaCount++;
                            //}
                            //else
                            //{
                            //    if (s>127 && s< 0x4E00)
                            //    {
                            //        ChinaCount++;
                            //    }
                            //}

			            }                        
                    }                    

                    if (ChinaCount>0)
                    {
                        int ins = Designator - 1 - ChinaCount; //插入的位置
                        string s1="", s2="";
                        s1 = P_str_Content.Substring(0, ins);
                        for (int k = 0; k < ChinaCount; k++)
                        {
                            s1 = s1 + " ";
                        }
                        s2 = P_str_Content.Substring(ins,P_str_Content.Length - ins);
                        P_str_Content = s1 + s2;
                    }


                    //BomToExcelSheet.Cells[excelrow, 10] = P_str_Content + P_str_Content.Length;

                    if (P_str_Content.Substring(0, 4) != "    ")//记事本一行开头不等于空，说明有内容
                    {
                            //序号
                            BomToExcelSheet.Cells[excelrow, 1] = Convert.ToString(idnum);// excelrow.ToString; //直接将遍历到的内容添加到工作表中
                            idnum++;

                            //使用量
                            txttempcolumn = 0;
                            while (P_str_Content.Substring(txttempcolumn, 1) != " ")
                            {
                                txttempcolumn++;
                            }
                            BomToExcelSheet.Cells[excelrow, txtusedcolumn] = P_str_Content.Substring(0, txttempcolumn); //直接将遍历到的内容添加到工作表中
                            
                            //计算用量多少
                            BomToExcelSheet.Cells[excelrow, txtProductionNum] = @"=" + GetColumnName(txtProductionNum) + "$2*F" + excelrow;

                            ////器件规格型号 正向读取如输入的有问题的话，有空格的话，就会出错 
                            //txttempcolumn = PartType;// 5;
                            //while (P_str_Content.Substring(txttempcolumn, 1) != " ")
                            //{
                            //    txttempcolumn++;
                            //}
                            //parttype = P_str_Content.Substring(PartType, (txttempcolumn - PartType));
                            //BomToExcelSheet.Cells[excelrow, txtparttypecolumn] = parttype; //直接将遍历到的内容添加到工作表中
                            
                            ////器件规格型号  反向方式可以保正读取是正确的。
                            txttempcolumn = Designator - 1;
                            while (P_str_Content.Substring(txttempcolumn, 1) == " ")
                            {
                                txttempcolumn--;
                            }
                            txttempcolumn++;
                            parttype = P_str_Content.Substring(PartType, (txttempcolumn - PartType));
                            BomToExcelSheet.Cells[excelrow, txtparttypecolumn] = parttype; //直接将遍历到的内容添加到工作表中


                            //器件的标号
                            txttempcolumn = Designator;// Designator + 1;
                            tempdesignatorcolumn = Designator;// Designator + 1;
                            do
                            {
                                while (P_str_Content.Substring(txttempcolumn, 1) != " ")
                                {
                                    txttempcolumn++;
                                }
                                if ((txttempcolumn - tempdesignatorcolumn) > 1)
                                {
                                    if (tempdesignatorcolumn == (Designator)) //最前面那个不用加,号隔开
                                    {
                                        exceldesignator = exceldesignator + (P_str_Content.Substring(tempdesignatorcolumn, (txttempcolumn - tempdesignatorcolumn)));
                                    }
                                    else
                                    {
                                        exceldesignator = exceldesignator + "," + (P_str_Content.Substring(tempdesignatorcolumn, (txttempcolumn - tempdesignatorcolumn)));
                                    }
                                }
                                tempdesignatorcolumn = ++txttempcolumn;
                            } while (txttempcolumn < Footprint);//62

                            //if ((txttempcolumn - tempdesignatorcolumn) == 0)
                            //{
                            //    exceldesignator = "ERROR(NC)";
                            //}    

                            //器件的封装
                            txttempcolumn = Footprint;// 63;
                            while (P_str_Content.Substring(txttempcolumn, 1) != " ")
                            {
                                txttempcolumn++;
                            }

                            if (txttempcolumn == Footprint)
                            {   //防止有些没有输入封装的生成错误料单
                                partfoot = "ERROR(NC)";
                                BomToExcelSheet.Cells[excelrow, txtfootprintcolumn] = partfoot;
                            }
                            else
                            {
                                if (P_str_Content.Substring((Footprint), 1) == "0")//
                                {
                                    partfoot = "";
                                    partfoot = P_str_Content.Substring(Footprint, (txttempcolumn - Footprint));
                                   // BomToExcelSheet.Cells[excelrow, txtfootprintcolumn] = "'" + partfoot;
                                    BomToExcelSheet.Cells[excelrow, txtfootprintcolumn] =  partfoot;
                                }
                                else
                                {

                                    partfoot = P_str_Content.Substring(Footprint, (txttempcolumn - Footprint));
                                    BomToExcelSheet.Cells[excelrow, txtfootprintcolumn] = partfoot;
                                }
                            }


                            //从器件库中查找器件名称  此程序可以用，但是处理很多时查速度不快
                            //int f = 0;
                            //string LibTempContent = "";
                            //for (int TempRow = 1; TempRow < 100000; TempRow++)
                            //{
                            //    range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, 1], PartLibSheet.Cells[TempRow, 1]]; //第1列内容为序号
                            //    LibTempContent = range.Text.ToString();
                            //    if (LibTempContent == "")
                            //    {
                            //        break;
                            //    }
                            //    range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, 3], PartLibSheet.Cells[TempRow, 3]]; //第三列内容为器件规格
                            //    LibTempContent = range.Text.ToString();
                            //    if (LibTempContent == parttype)
                            //    {
                            //        range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, 4], PartLibSheet.Cells[TempRow, 4]];//第四列内容为器件封装
                            //        LibTempContent = range.Text.ToString();//记录遍历到的值
                            //        if (LibTempContent == partfoot)
                            //        {
                            //            range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, 2], PartLibSheet.Cells[TempRow, 2]];//第二列内容为器件名称
                            //            LibTempContent = range.Text.ToString();
                            //            BomToExcelSheet.Cells[excelrow, txtpartname] = LibTempContent;//为器件的名称 
                            //            f = TempRow;
                            //            break;
                            //        }
                            //    }
                            //}

                            //从器件库中查找器件名称
                            int f = 0;
                            string LibTempContent = "";
                            for (int g = 2; g < Lib_List.Count; )//遍历泛型集合  I为记事本，文本行号
                            {
                                LibTempContent = Lib_List[g];//记录遍历到的值
                                if (LibTempContent == parttype)
                                {
                                    LibTempContent = Lib_List[g + 1];//记录遍历到的值
                                    if (LibTempContent == partfoot)
                                    {
                                        BomToExcelSheet.Cells[excelrow, txtpartname] = Lib_List[g - 1];//g-1为器件的名称 
                                        partname = Lib_List[g - 1];
                                        f = Lib_List.Count;
                                        break;
                                    }
                                }
                                g = g + 4;
                            }                       
                         
                            //如果是不相同那么就是没找到先记录下来
                            if (f != Lib_List.Count)
                            {
                                f = 0;
                                FindList.Add(excelrow.ToString());              //记录当前行号
                                FindList.Add("ERROR(NC)");
                                partname = "ERROR(NC)";
                                BomToExcelSheet.Cells[excelrow, txtpartname] = "ERROR(NC)";//g-1为器件的名称 
                                FindList.Add(parttype);                         //记录器件规格型号
                                FindList.Add(partfoot);                         //记录器件封装
                            }  
                        }
                        else//记事本一行开头等于空，说明元件的标号对应的为上一行相加
                        {
                            txttempcolumn = Designator;                                             //直接读取标号列的第一位置
                            tempdesignatorcolumn = Designator;                                             //直接读取标号列的第一位置
                            do
                            {
                                while (P_str_Content.Substring(txttempcolumn, 1) != " ")
                                {
                                    txttempcolumn++;
                                }
                                if ((txttempcolumn - tempdesignatorcolumn) > 1)
                                {
                                    exceldesignator = exceldesignator + "," + (P_str_Content.Substring(tempdesignatorcolumn, (txttempcolumn - tempdesignatorcolumn)));
                                }
                                tempdesignatorcolumn = ++txttempcolumn;
                            } while (txttempcolumn < Footprint-1);
                        }

                        if ((i + 1) < P_str_List.Count) //判断是否为最后一行
                        {
                            P_str_Content = P_str_List[i + 1];//试读取下一行，判断是否与上一行相关
                            if ((P_str_Content.Substring(0, 1)) != " ")
                            {
                                BomToExcelSheet.Cells[excelrow, txtdesignatorcolumn] = exceldesignator; //直接将遍历到的内容添加到工作表中

                                excelrow++;                 //行号加1
                                exceldesignator = "";       //清空内容
                                partfoot = "";
                                parttype = "";
                            }
                        }
                    }

                    //最后一行的结束
                    BomToExcelSheet.Cells[excelrow, txtdesignatorcolumn] = exceldesignator; //直接将遍历到的内容添加到工作表中
                    ////序号 等着加PCB板
                    BomToExcelSheet.Cells[excelrow + 1, 1] = Convert.ToString(idnum);                       //序号
                    BomToExcelSheet.Cells[excelrow + 1, txtpartname] = "PCB印制板";                         //器件名称
                    BomToExcelSheet.Cells[excelrow + 1, txtparttypecolumn] = textBoxProduct.Text + TextBoxBomName.Text + comboBoxBomRev.Text;// +PcbDate.Text; //textBoxPCB.Text;               //元件参数 列位置textBoxPCB.Text;               //元件参数 列位置
                    BomToExcelSheet.Cells[excelrow + 1, txtfootprintcolumn] = "版本:" + comboBoxBomRev.Text;//元件封装列位置
                    BomToExcelSheet.Cells[excelrow + 1, txtusedcolumn] = "1";                               //元件用量 列位置
                    BomToExcelSheet.Cells[excelrow + 1, txtdesignatorcolumn] = textBoxChinaName.Text + "   板内日期:" + PcbDate.Text ;  //元件标号 列位置
                    BomToExcelSheet.Cells[excelrow + 1, txtProductionNum] = @"=" + GetColumnName(txtProductionNum) + "$2*F" + excelrow; //计算用量多少           
            }
                else
                {

                    //  ad10处理函数
                    int[] Column = new int[10];
                    int tempcount = 0, tempcjj = 0;
                    P_str_Content = P_str_List[0];
                    bool fs = false;
                    int FootFlag = 0; 
                    for (int f = 0; f < P_str_Content.Length; )
                    {
                        if (P_str_Content.Substring(f, 1) == "\t")
                        {
                            switch (P_str_Content.Substring(tempcjj, f - tempcjj))
                            {
                                case "COMMENT":     //器件规格型号
                                    Column[tempcount] = txtparttypecolumn; //
                                    break;
                                case "DESCRIPTION": //描述
                                    Column[tempcount] = 20;//txtpartname;// 
                                    break;
                                case "DESIGNATOR":  //编号
                                    Column[tempcount] = txtdesignatorcolumn; //
                                    break;
                                case "FOOTPRINT":   //封装
                                    Column[tempcount] = txtfootprintcolumn; 
                                    FootFlag = tempcount; //;
                                    break;
                                case "LIBREF":      //库名称
                                    Column[tempcount] = 20;//txtlibrefcolumn;//
                                    break;
                                case "QUANTITY":    //数量
                                    Column[tempcount] = txtusedcolumn;//
                                    break;
                                default:
                                    fs = true;
                                    break;
                            }
                            if (fs)
                            {
                                fs = false;
                            }
                            else
                            {
                                tempcjj = ++f;
                                tempcount++;
                                fs = false;
                            }
                        }
                        else
                        {
                            f++;
                            if (f == P_str_Content.Length)
                            {
                                switch (P_str_Content.Substring(tempcjj, f - tempcjj))
                                {
                                    case "COMMENT": //器件规格型号
                                        Column[tempcount] = txtparttypecolumn;
                                        break;
                                    case "DESCRIPTION": //描述
                                        Column[tempcount] = 20;//txtpartname; 
                                        break;
                                    case "DESIGNATOR"://编号
                                        Column[tempcount] = txtdesignatorcolumn;
                                        break;
                                    case "FOOTPRINT": ;//封装
                                        Column[tempcount] = txtfootprintcolumn;
                                        FootFlag = tempcount;
                                        break;
                                    case "LIBREF"://库名称
                                        Column[tempcount] = 20;//txtlibrefcolumn;
                                        break;
                                    case "QUANTITY"://数量
                                        Column[tempcount] = txtusedcolumn;
                                        break;
                                    default:
                                        break;
                                }
                                f = f + 2;
                            }
                        }
                    }

                    for (int i = 2; i < P_str_List.Count; i++)//遍历泛型集合
                    {
                        P_str_Content = P_str_List[i];
                        int TempNumCount = 1,TempColumnCount=0;
                        string TempString;
                        BomToExcelSheet.Cells[excelrow, 1] = Convert.ToString(idnum);                       //序号
                        idnum++;
                        for (int j = 0; j < P_str_Content.Length; )
                        {
                            if (P_str_Content.Substring(j, 1) == "\"")
                            {
                                TempColumnCount = j + 1;
                                while ((P_str_Content.Substring(TempColumnCount, 1)) != "\"")
                                {
                                    TempColumnCount++;
                                }
                                if (TempColumnCount != (j + 1))
                                {
                                    TempString = P_str_Content.Substring((j + 1), (TempColumnCount - j - 1));

                                    //if (TempString.Substring(0, 1) == "0")
                                    //{
                                    //   TempString = "'" + TempString;
                                    //}

                                }
                                else
                                {
                                    TempString = "ERROR(NC)";//TempNumCount++;
                                }
                                
                                switch (TempNumCount)
                                {
                                    case 1:
                                        if (Column[0] != 20)
                                            BomToExcelSheet.Cells[excelrow, Column[0]] = TempString;
                                        if (Column[0] == 4)
                                            parttype = TempString;
                                        if (Column[0] == 5)
                                            partfoot = TempString;
                                        break;
                                    case 2:
                                        if (Column[1] != 20)
                                            BomToExcelSheet.Cells[excelrow, Column[1]] = TempString;
                                        if (Column[1] == 4)
                                            parttype = TempString;
                                        if (Column[1] == 5)
                                            partfoot = TempString;
                                        break;
                                    case 3:
                                        if (Column[2] != 20)
                                            BomToExcelSheet.Cells[excelrow, Column[2]] = TempString;
                                        if (Column[2] == 4)
                                            parttype = TempString;
                                        if (Column[2] == 5)
                                            partfoot = TempString;
                                        break;
                                    case 4:
                                        if (Column[3] != 20)
                                            BomToExcelSheet.Cells[excelrow, Column[3]] = TempString;
                                        if (Column[3] == 4)
                                            parttype = TempString;
                                        if (Column[3] == 5)
                                            partfoot = TempString;
                                        break;
                                    case 5:
                                        if (Column[4] != 20)
                                            BomToExcelSheet.Cells[excelrow, Column[4]] = TempString;
                                        if (Column[4] == 4)
                                            parttype = TempString;
                                        if (Column[4] == 5)
                                            partfoot = TempString;
                                        break;
                                    case 6:
                                        if (Column[5] != 20)
                                            BomToExcelSheet.Cells[excelrow, Column[5]] = TempString;
                                        if (Column[5] == 4)
                                            parttype = TempString;
                                        if (Column[5] == 5)
                                            partfoot = TempString;
                                        break;
                                    default:
                                        break;
                                }
                                TempNumCount++;
                                j = TempColumnCount;
                            }
                            j++;
                        }

                        BomToExcelSheet.Cells[excelrow, txtProductionNum] = @"=" + GetColumnName(txtProductionNum) + "$2*F" + excelrow; //计算用量多少

                        //从器件库中查找器件名称
                        int f = 0;
                        string LibTempContent = "", temptypes = "", tempfoot = "";
                        for (int g = 2; g < Lib_List.Count; )//遍历泛型集合  I为记事本，文本行号
                        {
                            LibTempContent = Lib_List[g];//记录遍历到的值

                            if (parttype.Substring(0, 1) == "'")
	                        {
                                temptypes = parttype.Substring(1,parttype.Length-1);
	                        }
                            else
                            {
                                temptypes = parttype;
                            }

                            if (partfoot.Substring(0, 1) == "'")
                            {
                                tempfoot = partfoot.Substring(1, partfoot.Length - 1);
                            }
                            else
                            {
                                tempfoot = partfoot;
                            }

                            if (LibTempContent == temptypes)//parttype
                            {
                                LibTempContent = Lib_List[g + 1];//记录遍历到的值
                                if (LibTempContent == tempfoot)//partfoot
                                {
                                    BomToExcelSheet.Cells[excelrow, txtpartname] = Lib_List[g - 1];//g-1为器件的名称 
                                    partname = Lib_List[g - 1];
                                    f = Lib_List.Count;
                                    break;
                                }
                            }
                            g = g + 4;
                        }

                        //if (parttype == "")
                        //    BomToExcelSheet.Cells[excelrow, txtparttypecolumn] = "ERROR";
                        //if (partfoot == "")
                        //    BomToExcelSheet.Cells[excelrow, txtfootprintcolumn] = "ERROR";
                        //int txtparttypecolumn = 4;          //元件参数 列位置
                        //int txtfootprintcolumn = 5;         //元件封装列位置
                        //如果是不相同那么就是没找到先记录下来
                        if (f != Lib_List.Count)
                        {
                            f = 0;
                            FindList.Add(excelrow.ToString());              //记录当前行号
                            FindList.Add("ERROR(NC)");
                            BomToExcelSheet.Cells[excelrow, txtpartname] = "ERROR(NC)"; 
                            FindList.Add(parttype);                         //记录器件规格型号
                            FindList.Add(partfoot);                         //记录器件封装
                        }


                        //All_List.Add(partname);
                        //All_List.Add(parttype);
                        //All_List.Add(partfoot);

                        excelrow++; //行号加1
                    }//结束行

                    ////序号 等着加PCB板
                    BomToExcelSheet.Cells[excelrow , 1] = Convert.ToString(idnum);                       //序号
                    BomToExcelSheet.Cells[excelrow , txtpartname] = "PCB印制板";                         //器件名称
                    BomToExcelSheet.Cells[excelrow, txtparttypecolumn] = textBoxProduct.Text + TextBoxBomName.Text + comboBoxBomRev.Text;// +PcbDate.Text; //textBoxPCB.Text;               //元件参数 列位置
                    BomToExcelSheet.Cells[excelrow , txtfootprintcolumn] = "版本:" + comboBoxBomRev.Text;//元件封装列位置
                    BomToExcelSheet.Cells[excelrow , txtusedcolumn] = "1";                               //元件用量 列位置
                    BomToExcelSheet.Cells[excelrow, txtdesignatorcolumn] = textBoxChinaName.Text +   "    板内日期:" + PcbDate.Text;  //元件标号 列位置
                    BomToExcelSheet.Cells[excelrow , txtProductionNum] = @"=" + GetColumnName(txtProductionNum) + "$2*F" + excelrow; //计算用量多少
                } //结束AD10


            //MessageBox.Show("处理完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            ProStatus.Text = "单表处理完成！";

          

        }

        public void sortfunv12(string bomnamet)
        {
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿     
            Excel.Range range;
            int allbom = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == bomnamet)
                {
                    allbom = i;
                }
            }
            Excel.Worksheet AllBomSheet = workbook.Worksheets[allbom];//要操作的表的索引 
            //暂存分表内容
            List<string> TempList = new List<string>();
            string stemp;
            for (int p = 3; p < 200000; p++)
            {
                range = AllBomSheet.Range[AllBomSheet.Cells[p, 1], AllBomSheet.Cells[p, 1]];
                stemp = range.Text.ToString();
                if (stemp != "")
                {
                    TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 3], AllBomSheet.Cells[p, 3]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 4], AllBomSheet.Cells[p, 4]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 5], AllBomSheet.Cells[p, 5]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 6], AllBomSheet.Cells[p, 6]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 7], AllBomSheet.Cells[p, 7]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                }
                else
                {
                    break;
                }
            }

            //开始排序
            List<string> TempList2 = new List<string>();
            for (int ai = 0; ai < GAllSortList.Count; )
            {
                for (int jj = 0; jj < TempList.Count; )
                {
                    if (GAllSortList[ai] == TempList[jj + 1])
                    {
                        TempList2.Add(TempList[jj + 0]);
                        TempList2.Add(GAllSortList[ai + 1]); TempList[jj + 1] = GAllSortList[ai + 1];
                        TempList2.Add(TempList[jj + 2]);
                        TempList2.Add(TempList[jj + 3]);
                        TempList2.Add(TempList[jj + 4]);
                        TempList2.Add(TempList[jj + 5]);
                    }
                    jj = jj + 6;
                }
                ai = ai + 2; ;
            }

            //重新填入
            int ttmp = 0, lentht = TempList2.Count / 6 + 3;
            for (int lls = 3; lls < lentht; lls++)
            {
                AllBomSheet.Cells[lls, 1] = TempList2[ttmp * 6 + 0];
                AllBomSheet.Cells[lls, 3] = TempList2[ttmp * 6 + 1];
                AllBomSheet.Cells[lls, 4] = TempList2[ttmp * 6 + 2];
                AllBomSheet.Cells[lls, 5] = TempList2[ttmp * 6 + 3];
                AllBomSheet.Cells[lls, 6] = TempList2[ttmp * 6 + 4];
                AllBomSheet.Cells[lls, 7] = TempList2[ttmp * 6 + 5];
                ttmp++;
            }

            int ttid = lentht, idd2f = 0;
            for (int inbom = 0; inbom < TempList.Count; )
            {
                for (int d = 0; d < TempList2.Count; )
                {
                    if (TempList[inbom + 1] == TempList2[d + 1])
                    {
                        idd2f = 1;
                        break;
                    }
                    d = d + 6;
                }
                if (idd2f != 1)
                {
                    idd2f = 0;
                    AllBomSheet.Cells[ttid, 1] = TempList[inbom + 0];
                    AllBomSheet.Cells[ttid, 3] = TempList[inbom + 1];
                    AllBomSheet.Cells[ttid, 4] = TempList[inbom + 2];
                    AllBomSheet.Cells[ttid, 5] = TempList[inbom + 3];
                    AllBomSheet.Cells[ttid, 6] = TempList[inbom + 4];
                    AllBomSheet.Cells[ttid, 7] = TempList[inbom + 5];
                    ttid++;
                }
                else
                {
                    idd2f = 0;
                }
                inbom = inbom + 6;
            }
        }


        //单表替换辅助处理
        public void AuxiliaryPro(string textboxbom)
        {
            
            //-----把分表的所有内容存起来---------------------------------------------------

            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int AllBom = 0;//,test=0;
           // string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == textboxbom )
                {
                    AllBom = i;
                }
            }
            Excel.Worksheet AllSheet = workbook.Worksheets[AllBom];//要操作的表的索引。
            Excel.Range range;                      
            string TempStr = "";
            int rowstemp = 1;
            for (int i = 3; i < 20000; i++)
            {
                range = AllSheet.Range[AllSheet.Cells[i, 1], AllSheet.Cells[i, 1]];
                TempStr = range.Text.ToString();
                if (TempStr == "")
                {
                    rowstemp = i - 2;
                    break;
                }
            }
            //进行排一下序AllSheet.Cells[i, 10 + BomNumCount]
            range = AllSheet.Range[AllSheet.Cells[3, 1], AllSheet.Cells[rowstemp, 9]]; //  4 有点问题 改为-> 10 + BomNumCount + 1              
            range.Sort(
             range.Columns[2, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[4, missing], missing, Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[3, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing, missing,
             Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortColumns,
             Microsoft.Office.Interop.Excel.XlSortMethod.xlPinYin,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal);

            //自定义排序
            menfun();
            sortfunv12(textboxbom);

            //存入单表的所有内容
            OkAllList.Clear();
            int ids=1;
            for (int i = 3; i < 20000; i++)
            {
                range = AllSheet.Range[AllSheet.Cells[i, 1], AllSheet.Cells[i, 1]];
                TempStr = range.Text.ToString();
                if (TempStr == "")
                { 
                    break;
                }
                else
                {
                    AllSheet.Cells[i, 1] = ids; ids++;
                }
                    
                for (int j = 1; j < 6; j++)
                {
                    range = AllSheet.Range[AllSheet.Cells[i, j], AllSheet.Cells[i, j]];
                    TempStr = range.Text.ToString();
                    if (j != 2)
                    {
                        OkAllList.Add(TempStr);//将读取到的行内容添加到泛型集合中  
                    }
                    
                }
            }
            //-----把分表的所有内容存起来 结束---------------------------------------------


            //读取替换表内容            
            ReaderReplaceList();


            //-------替换表生成------------------------------------------------------------
            string  name, part, foot;
            /*处理两个工作表分别为：料单样板、器件库*/
            int BomNum = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == textboxbom)//TextBoxBomName.TextTextBoxBomName.Text
                {
                    BomNum = i;
                }
            }
            Excel.Worksheet ReplaceSheet = workbook.Worksheets[BomNum];//要操作的表的索引。           

            for (int TempRow = 3; TempRow < 20000; TempRow++)
            {
                range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 1], ReplaceSheet.Cells[TempRow, 1]];
                TempStr = range.Text.ToString();
                if (TempStr == "")
                {
                    break;
                }

                range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 3], ReplaceSheet.Cells[TempRow, 3]];
                name = range.Text.ToString();
                range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 4], ReplaceSheet.Cells[TempRow, 4]];
                part = range.Text.ToString();
                range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 5], ReplaceSheet.Cells[TempRow, 5]];
                foot = range.Text.ToString();

                for (int i = 0; i < AllReplace_List.Count - 1; )
                {
                    if ((name == AllReplace_List[i + 1]) && (part == AllReplace_List[i + 3]) && (foot == AllReplace_List[i + 5]))
                    {
                        ReplaceSheet.Cells[TempRow, 9] = "替;"+ AllReplace_List[i + 0]; //备注一下替换表的行号

                        if (AllReplace_List[i + 2] != "保持不变")
                        {
                            ReplaceSheet.Cells[TempRow, 3] = AllReplace_List[i + 2];
                            range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 3], ReplaceSheet.Cells[TempRow, 3]];
                            range.Interior.ColorIndex = 3;
                        }
                        if (AllReplace_List[i + 4] != "保持不变")
                        {
                            ReplaceSheet.Cells[TempRow, 4] = AllReplace_List[i + 4];
                            range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 4], ReplaceSheet.Cells[TempRow, 4]];
                            range.Interior.ColorIndex = 3;
                        }
                        if (AllReplace_List[i + 6] != "保持不变")
                        {
                            ReplaceSheet.Cells[TempRow, 5] = AllReplace_List[i + 6];
                            range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 5], ReplaceSheet.Cells[TempRow, 5]];
                            range.Interior.ColorIndex = 3;
                        }
                        
                        break;
                    }
                    i = i + 9;
                }
            }
            //-------替换表生成 结束------------------------------------------------------------
        }



        //单张BOM转EXCEL
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false; //防止多按单张转换的次数
            bomProExcel();

            //辅助替换处理程序
            AuxiliaryPro(TextBoxBomName.Text);           
         
            //重新可以使用单表转换
            //button1.Enabled = true;
            //转一次以后就不可以转了
            button1.Enabled = false; //防止多按单张转换的次数            
            //处理单表时多表不能进行操作
            button3.Enabled = false;

            //使能单表辅助整理
            button25.Enabled = true;

            //默认情况不输出
            buttonPCBOUT.Enabled = true;   
            //整理的那个表示“成功”的按键
            //buttonAdvancedStatus.Enabled = true;
            //整理按钮
            button7.Enabled = true;

            //要整理表的表名
            comboBox4.Items.Clear();
            comboBox4.Text = TextBoxBomName.Text;

            //只有保存了配置并生成了表才能输出
            button8.Enabled = true;

            MessageBox.Show("单表转换处理完成。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
           // PcbOut();
            //int sheetnum = 0;
            //label1.Text = string.Empty;
            //Excel.Workbook book = this.Application.Workbooks[1];
            //for (int i = 1; i <= book.Worksheets.Count; i++)
            //{
            //    //C# 4.0新特性，PIA动态编译。
            //    label1.Text += book.Worksheets[i].Name + " ";
            //    if (book.Worksheets[i].Name == "料单样板")
            //    {
            //        sheetnum = i;
            //    }
            //}
            //Excel.Worksheet sheet = book.Worksheets[sheetnum];//要操作的表的索引。
            //label1.Text = "当前正在操作的工作表名为： " + sheetnum + sheet.Name;
            ////sheet.Name = "bom清单";//也可以更改表名。
            //sheet.Cells[10, 3] = "插件电感";//在指定单元格中写内容
            //sheet.Cells[10, 4] = "6.8UH/1A";//在指定单元格中写内容 
        
        }

        //打开单个文件
        public void OpenSingleFile()
        {
            string TempPath = "";
            OpenFileDialog openExcel = new OpenFileDialog();    //实例化打开对话框对象
            openExcel.Filter = "bom文件|*.bom|文本文件|*.txt";                //设置打开文件筛选器
            openExcel.Multiselect = false;                      //设置打开对话框中不能多选
            if (openExcel.ShowDialog() != DialogResult.OK)      //判断是否选择了文件
            {
                return;
            }

            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int BomNum = 0, CopyBom = 0;
            string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                tabname[i - 1] = workbook.Worksheets[i].Name;       //存工作簿
                if (workbook.Worksheets[i].Name == "多表配置样板")
                {
                    BomNum = i;
                }
                if (workbook.Worksheets[i].Name == "多表配置")
                {
                    CopyBom = i;
                }
            }

            //更改上一版本为副本
            if (CopyBom != 0)
            {
                Excel.Worksheet CopyBomSheet = workbook.Worksheets[CopyBom];//要操作的表的索引。
                CopyBomSheet.Name = CopyBomSheet.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
            }
            //PCB输出样板存副本
            Excel.Worksheet BomConfigSheetCopy = workbook.Worksheets[BomNum];//要操作的表的索引。
            //复制一个表
            object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            BomConfigSheetCopy.Copy(Missing, BomConfigSheetCopy);
            //对新建的PCB输出样板进行操作
            Excel.Worksheet BomConfigSheet = workbook.Worksheets[BomNum + 1];//要操作的表的索引。
            BomConfigSheet.Name = "多表配置";           
            ProStatus.Text = "正在处理，请稍后...";




            //显示选择的文件目录及文件名 例如C:\BOM\A.XLSX
            BomPath.Text = openExcel.FileName;                          
            TempPath = openExcel.FileName;            
            //BOM文件名
            TextBoxBomName.Text = TempPath.Substring(TempPath.LastIndexOf("\\") + 1, TempPath.LastIndexOf(".") - (TempPath.LastIndexOf("\\") + 1)); //获取文件名
            //软件版本
            if (TempPath.Substring(TempPath.LastIndexOf(".") + 1, TempPath.Length - TempPath.LastIndexOf(".") - 1) == "txt")//获取文件扩展名
            { comboBoxSoftRev.Text = "ad10"; }
            else
            { comboBoxSoftRev.Text = "protel99se"; }            

            BomConfigSheet.Cells[2, 1] = 1;                                         //序号
            BomConfigSheet.Cells[2, 2] = "L1305(样板)";                             //项目名称
            BomConfigSheet.Cells[2, 3] = DateTime.Now.ToString("yyyy-MM-dd");       //打印日期
            //获取BOM文件名 3列
            BomConfigSheet.Cells[2, 4] = TextBoxBomName.Text;                       //bom表名
            BomConfigSheet.Cells[2, 5] = "机车信号主机板(样板)";                    //中文名
            BomConfigSheet.Cells[2, 6] = TextBoxBomName.Text;                       //PCB板名
            BomConfigSheet.Cells[2, 7] = "V10(样板)";                               //PCB版本
            BomConfigSheet.Cells[2, 8] = "150*100";                                 //PCB尺寸
            BomConfigSheet.Cells[2, 9] = DateTime.Now.ToString("yyyy-MM-dd");       //PCB板内日期
            BomConfigSheet.Cells[2, 10] = "2";                                      //板层
            BomConfigSheet.Cells[2, 11] = "10";                                     //下单数量
            BomConfigSheet.Cells[2, 12] = "1.6";                                    //厚度
            BomConfigSheet.Cells[2, 13] = "无铅喷锡";                               //加工工艺
            BomConfigSheet.Cells[2, 14] = DateTime.Now.ToString("yyyy-MM-dd");      //加工日期
            BomConfigSheet.Cells[2, 15] = openExcel.FileName;                       //目录及文件名 路径 
            BomConfigSheet.Cells[2, 16] = comboBoxSoftRev.Text;                     //软件版本   
        
            BomFileName[0] = TextBoxBomName.Text;//后缀 确认板本
            //存入打开文件个数
            BomNumCount = 1;
        }
    
        //打开Bom
        private void button2_Click(object sender, EventArgs e)
        {   
            //打开Bom
            button2.Enabled = false;
            //调用打开
            OpenSingleFile();
            //打开Bom
            button2.Enabled = true;
            //保存配置
            button21.Enabled = true;
            //开始转换
            //button1.Enabled = true;
            ProStatus.Text = "处理完成。";
        }

        //BOM表替换
        public void BomReplace() 
        {
            if (FindList.Count > 0)
            {
                int c1 = 0;
                //buttonAdvancedStatus.Text = "下一步";
                label1.Text = FindList[1];  // +"当前的器件名称:\"" + "\"是否要更新为:";
                label2.Text = FindList[2];  // "当前的规格型号:\"" + +"\"是否要更新为:";
                label3.Text = FindList[3];  // "当前的器件封装:\"" + +"\"是否要更新为:";
                comboBox1.Text = "";
                comboBox2.Text = "";
                comboBox3.Text = "";
                comboBox1.Items.Clear();
                comboBox2.Items.Clear();
                comboBox3.Items.Clear();
                //找相似元件数量
                c1 = 0;
                for (int h = 0; h < Lib_List.Count; h++)//遍历泛型集合  I为记事本，文本行号
                {
                    if ((stringcompare(FindList[2], Lib_List[h]) == 2))  //等于2说明libContent包含有libContent的内容
                    {
                        if ((FindList[3]) == (Lib_List[h + 1]))
                        {
                            comboBox1.Items.Add(Lib_List[h - 1]);
                            comboBox2.Items.Add(Lib_List[h]);
                            comboBox3.Items.Add(Lib_List[h + 1]);
                            c1++;
                        }
                    }
                }

                if (c1 == 0) //相似的也没找到
                {
                    label1.Text = FindList[1];      // "没找到器件名称为:\"" + +"\" 是否手动输入?";
                    label2.Text = FindList[2];      //"没找到规格型号为:\"" + +"\" 是否手动输入?";
                    label3.Text = FindList[3];       //"没找到器件封装为:\"" +  + "\" 是否手动输入?";
                    comboBox1.Items.Add("没找到相似的");
                    comboBox2.Items.Add("没找到相似的");
                    comboBox3.Items.Add("没找到相似的");
                    comboBox1.Text = "请输入器件名称";
                    comboBox2.Text = "请输入规格型号";
                    comboBox3.Text = "请输入器件封装";                    
                    buttonAdvancedStatus.Text = "下一步";
                }
                else
                {
                    comboBox1.Text = "请选择器件名称";
                    comboBox2.Text = "请选择规格型号";
                    comboBox3.Text = "请选择器件封装";  
                    buttonAdvancedStatus.Text = "下一步";
                }
            }
        }

        //整理
        private void button7_Click(object sender, EventArgs e)
        {
            buttonAdvancedStatus.Enabled = true;
            if (button7.Text == "整理")
            {               
                BomReplace();
                button7.Text = "删除";
            }
            else//执行删除部分
            {
                ReplacePro("删除");
            }
        }

        //BOM表替换处理
        public void ReplacePro( string proif)
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            int sheetnum = 0;
            List<string> TempSbomListReplace = new List<string>(); 

            int UpFlas=0;
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                tabname[i - 1] = workbook.Worksheets[i].Name;       //存工作簿
                if (workbook.Worksheets[i].Name == comboBox4.Text)
                {
                    sheetnum = i;
                }
            }

            //料单样板
            Excel.Worksheet BomToExcelSheet = workbook.Worksheets[sheetnum];//要操作的表的索引。
            //下面这两个只是给个定义及初始化一下，后面要更改对应关系
            Excel.Worksheet CopySheet = workbook.Worksheets[sheetnum];//要操作的表的索引。
            Excel.Worksheet UpdateSheet = workbook.Worksheets[sheetnum];//要操作的表的索引。

            Excel.Range range;
            //string BomRev = textBoxBomRev.Text;   //料单的版本
            //string BomName = textBoxChinaName.Text; // "L1305主机板"; //BOM表转出后中文名  
            //自定义页眉
            if (ProCount < FindList.Count)
            {
                //器件库
                //string tempstr = "";
                if (proif=="删除")
                {
                    if (comboBox4.Text=="总表")
                    {
                        //填入
                        BomToExcelSheet.Cells[FindList[ProCount], 1] = "删除"; //
                        BomToExcelSheet.Cells[FindList[ProCount], 2] = "删除"; //
                        range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 2], BomToExcelSheet.Cells[FindList[ProCount], 2]];   //第2-4列内容为器件名称，规格型号，封装
                        range.Interior.ColorIndex = 3;
                        BomToExcelSheet.Cells[FindList[ProCount], 3] = "删除";
                        range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 3], BomToExcelSheet.Cells[FindList[ProCount], 3]];   //第2-4列内容为器件名称，规格型号，封装
                        range.Interior.ColorIndex = 3;
                        BomToExcelSheet.Cells[FindList[ProCount], 4] = "删除";
                        range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 4], BomToExcelSheet.Cells[FindList[ProCount], 4]];   //第2-4列内容为器件名称，规格型号，封装
                        range.Interior.ColorIndex = 3;  
                    }
                    else
                    {
                        //填入
                        BomToExcelSheet.Cells[FindList[ProCount], 1] = "删除"; //
                        BomToExcelSheet.Cells[FindList[ProCount], 3] = "删除"; //
                        range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 3], BomToExcelSheet.Cells[FindList[ProCount], 3]];   //第2-4列内容为器件名称，规格型号，封装
                        range.Interior.ColorIndex = 3;
                        BomToExcelSheet.Cells[FindList[ProCount], 4] = "删除";
                        range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 4], BomToExcelSheet.Cells[FindList[ProCount], 4]];   //第2-4列内容为器件名称，规格型号，封装
                        range.Interior.ColorIndex = 3;
                        BomToExcelSheet.Cells[FindList[ProCount], 5] = "删除";
                        range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 5], BomToExcelSheet.Cells[FindList[ProCount], 5]];   //第2-4列内容为器件名称，规格型号，封装
                        range.Interior.ColorIndex = 3;
                    }
                    ////记录
                    //BomToExcelSheet.Cells[rowcount, 1] = rowcount - 999;
                    //BomToExcelSheet.Cells[rowcount, 2] = FindList[ProCount + 1];
                    //BomToExcelSheet.Cells[rowcount, 3] = " -> ";
                    //BomToExcelSheet.Cells[rowcount, 4] = "删除";
                    //BomToExcelSheet.Cells[rowcount, 5] = FindList[ProCount + 2];
                    //BomToExcelSheet.Cells[rowcount, 6] = " -> ";
                    //BomToExcelSheet.Cells[rowcount, 7] = "删除";
                    //BomToExcelSheet.Cells[rowcount, 8] = FindList[ProCount + 3];
                    //BomToExcelSheet.Cells[rowcount, 9] = " -> ";
                    //BomToExcelSheet.Cells[rowcount, 10] = "删除";
                    //BomToExcelSheet.Cells[rowcount, 11] = dateTimePicker1.Text;
                    //rowcount++;

                    TempSbomListReplace.Add(rowcount.ToString()); rowcount++;          //1   0  序号
                    TempSbomListReplace.Add(FindList[ProCount + 1]);          //0   1  原
                    TempSbomListReplace.Add(" ->");
                    TempSbomListReplace.Add("删除");
                    TempSbomListReplace.Add(FindList[ProCount + 2]);
                    TempSbomListReplace.Add(" ->");
                    TempSbomListReplace.Add("删除");
                    TempSbomListReplace.Add(FindList[ProCount + 3]);
                    TempSbomListReplace.Add(" ->");
                    TempSbomListReplace.Add("删除");
                    //dateTimePicker1.Text.;
                    TempSbomListReplace.Add(Convert.ToDateTime(dateTimePicker1.Text).ToString("yyyy-MM-dd")); //时间
                    TempSbomListReplace.Add("删除"); //备注
                    rowcount++;
                }

                





                if (proif == "替换")
                {
                    TempSbomListReplace.Add(rowcount.ToString()); //rowcount++;          //1   0  序号

                    if ((comboBox1.Text != "请选择器件名称") && (comboBox1.Text != "请输入器件名称")) //器件名称
                    {
                        if (comboBox4.Text == "总表")
                        {
                            BomToExcelSheet.Cells[FindList[ProCount], 2] = comboBox1.Text; //
                            range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 2], BomToExcelSheet.Cells[FindList[ProCount], 2]];   //第2-4列内容为器件名称，规格型号，封装
                            range.Interior.ColorIndex = 3;                            
                        }
                        else
                        {
                            BomToExcelSheet.Cells[FindList[ProCount], 3] = comboBox1.Text; //
                            range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 3], BomToExcelSheet.Cells[FindList[ProCount], 3]];   //第2-4列内容为器件名称，规格型号，封装
                            range.Interior.ColorIndex = 3;
                        }
                        //BomToExcelSheet.Cells[rowcount, 2] = FindList[ProCount + 1];
                        //BomToExcelSheet.Cells[rowcount, 3] = " -> ";
                        //BomToExcelSheet.Cells[rowcount, 4] = comboBox1.Text;

                        TempSbomListReplace.Add(FindList[ProCount + 1]);          //0   1  原
                        TempSbomListReplace.Add(" ->");
                        TempSbomListReplace.Add(comboBox1.Text);

                    }
                    else
                    {
                        //BomToExcelSheet.Cells[rowcount, 2] = FindList[ProCount + 1];
                        //BomToExcelSheet.Cells[rowcount, 3] = " -> ";
                        //BomToExcelSheet.Cells[rowcount, 4] = "保持不变";

                        TempSbomListReplace.Add(FindList[ProCount + 1]);          //0   1  原
                        TempSbomListReplace.Add(" ->");
                        TempSbomListReplace.Add("保持不变");

                        UpFlas = UpFlas + 1; 
                    }
                    if ((comboBox2.Text != "请选择规格型号") && (comboBox2.Text != "请输入规格型号"))
                    {
                        if (comboBox4.Text == "总表")
                        {
                            BomToExcelSheet.Cells[FindList[ProCount], 3] = comboBox2.Text;
                            range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 3], BomToExcelSheet.Cells[FindList[ProCount], 3]];   //第2-4列内容为器件名称，规格型号，封装
                            range.Interior.ColorIndex = 3;
                        }
                        else
                        {
                            BomToExcelSheet.Cells[FindList[ProCount], 4] = comboBox2.Text;
                            range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 4], BomToExcelSheet.Cells[FindList[ProCount], 4]];   //第2-4列内容为器件名称，规格型号，封装
                            range.Interior.ColorIndex = 3;
                        }

                        //BomToExcelSheet.Cells[rowcount, 5] = FindList[ProCount + 2];
                        //BomToExcelSheet.Cells[rowcount, 6] = " -> ";
                        //BomToExcelSheet.Cells[rowcount, 7] = comboBox2.Text;

                        TempSbomListReplace.Add(FindList[ProCount + 2]);
                        TempSbomListReplace.Add(" ->");
                        TempSbomListReplace.Add(comboBox2.Text);

                    }
                    else
                    {
                        //BomToExcelSheet.Cells[rowcount, 5] = FindList[ProCount + 2];
                        //BomToExcelSheet.Cells[rowcount, 6] = " -> ";
                        //BomToExcelSheet.Cells[rowcount, 7] = "保持不变";

                        TempSbomListReplace.Add(FindList[ProCount + 2]);
                        TempSbomListReplace.Add(" ->");
                        TempSbomListReplace.Add("保持不变");

                        UpFlas = UpFlas + 1; 
                    }
                    if ((comboBox3.Text != "请选择器件封装") && (comboBox3.Text != "请输入器件封装"))
                    {
                        if (comboBox4.Text == "总表")
                        {
                            BomToExcelSheet.Cells[FindList[ProCount], 4] = comboBox3.Text;
                            range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 4], BomToExcelSheet.Cells[FindList[ProCount], 4]];   //第2-4列内容为器件名称，规格型号，封装
                            range.Interior.ColorIndex = 3;
                        }
                        else
                        {   
                            BomToExcelSheet.Cells[FindList[ProCount], 5] = comboBox3.Text;
                            range = BomToExcelSheet.Range[BomToExcelSheet.Cells[FindList[ProCount], 5], BomToExcelSheet.Cells[FindList[ProCount], 5]];   //第2-4列内容为器件名称，规格型号，封装
                            range.Interior.ColorIndex = 3;
                        }
                        //BomToExcelSheet.Cells[rowcount, 8] = FindList[ProCount + 3];
                        //BomToExcelSheet.Cells[rowcount, 9] = " -> ";
                        //BomToExcelSheet.Cells[rowcount, 10] = comboBox3.Text;

                        TempSbomListReplace.Add(FindList[ProCount + 3]);
                        TempSbomListReplace.Add(" ->");
                        TempSbomListReplace.Add(comboBox3.Text);

                    }
                    else
                    {
                        //BomToExcelSheet.Cells[rowcount, 8] = FindList[ProCount + 3];
                        //BomToExcelSheet.Cells[rowcount, 9] = " -> ";
                        //BomToExcelSheet.Cells[rowcount, 10] = "保持不变";

                        TempSbomListReplace.Add(FindList[ProCount + 3]);
                        TempSbomListReplace.Add(" ->");
                        TempSbomListReplace.Add("保持不变");

                        UpFlas = UpFlas + 1; 
                    }
                    if (UpFlas != 3) //等于3为保持不变
                    {
                        //BomToExcelSheet.Cells[rowcount, 11] = dateTimePicker1.Text;// DateTime.Now.ToString("yyyy-MM-dd");
                        //BomToExcelSheet.Cells[rowcount, 1] = rowcount - 999; rowcount++;

                        TempSbomListReplace.Add(Convert.ToDateTime(dateTimePicker1.Text).ToString("yyyy-MM-dd")); //时间
                        TempSbomListReplace.Add("替换"); //备注
                        rowcount++;
                    }
                }


                int c1 = 0;
                ProCount = ProCount + 4;
                if (ProCount < FindList.Count)
                {
                    comboBox1.Items.Clear();
                    comboBox2.Items.Clear();
                    comboBox3.Items.Clear();
                    comboBox1.Text = "";
                    comboBox2.Text = "";
                    comboBox3.Text = "";
                    //找相似元件数量
                    c1 = 0;
                    for (int h = 0; h < Lib_List.Count; h++)//遍历泛型集合  I为记事本，文本行号
                    {
                        if ((stringcompare(FindList[ProCount + 2], Lib_List[h]) == 2))  //等于2说明libContent包含有libContent的内容
                        {
                            if (FindList[ProCount + 3] == Lib_List[h + 1])
                            {
                                comboBox1.Items.Add(Lib_List[h - 1]);
                                comboBox2.Items.Add(Lib_List[h]);
                                comboBox3.Items.Add(Lib_List[h + 1]);
                                c1++;
                            }
                        }
                    }
                    //是否有相同的类的器件，进行选择项选出
                    if (c1 > 0)
                    {
                        label1.Text = FindList[ProCount + 1]; //"当前的器件名称:\"" + + "\"是否要更新为:";
                        label2.Text = FindList[ProCount + 2]; //"当前的规格型号:\"" +  +"\"是否要更新为:";
                        label3.Text = FindList[ProCount + 3]; //"当前的器件封装:\"" +  +"\"是否要更新为:";
                        comboBox1.Text = "请选择器件名称";
                        comboBox2.Text = "请选择规格型号";
                        comboBox3.Text = "请选择器件封装";
                    }
                    else
                    {
                        label1.Text = FindList[ProCount + 1];// "没找到器件名称为:\"" + +"\" 是否手动输入?";
                        label2.Text = FindList[ProCount + 2];//"没找到规格型号为:\"" +  +"\" 是否手动输入?";
                        label3.Text = FindList[ProCount + 3];// "没找到器件封装为:\"" +  +"\" 是否手动输入?";
                        //comboBox1.Items.Add("没找到相似的");
                        comboBox2.Items.Add("没找到相似的");
                        comboBox3.Items.Add("没找到相似的");
                        comboBox1.Text = "请输入器件名称";
                        comboBox2.Text = "请输入规格型号";
                        comboBox3.Text = "请输入器件封装";
                    }
                    for (int i = 0; i < PartClass.Length; i++)
			        {
                        comboBox1.Items.Add(PartClass[i]);
			        }                    
                }
            }
            else
            {
                //更改记录生成
                for (int i = 1; i <= workbook.Worksheets.Count; i++)
                {
                    if (workbook.Worksheets[i].Name == "更改记录样板")
                    {
                        sheetnum = i;
                    }

                    if (workbook.Worksheets[i].Name == (@"更改记录(" + comboBox4.Text + ")"))
                    {
                        Excel.Worksheet DelSheet = workbook.Worksheets[i];
                        DelSheet.Name = DelSheet.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
                    }
                }
                CopySheet = workbook.Worksheets[sheetnum];//要操作的表的索引。
                object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
                CopySheet.Copy(Missing, CopySheet);
                //对新建的PCB输出样板进行操作
                UpdateSheet = workbook.Worksheets[sheetnum + 1];//要操作的表的索引。
                UpdateSheet.Name = "更改记录(" + comboBox4.Text+")";
                string TempStr = "";

                for (int i = 1000; i < 1500; i++)
                {
                    range = BomToExcelSheet.Range[BomToExcelSheet.Cells[i, 1], BomToExcelSheet.Cells[i, 1]];   //第2-4列内容为器件名称，规格型号，封装
                    TempStr = range.Text.ToString();
                    if (TempStr == "")
                        break;
                    for (int k = 1; k < 12; k++)
                    {
                        range = BomToExcelSheet.Range[BomToExcelSheet.Cells[i, k], BomToExcelSheet.Cells[i, k]];   //第2-4列内容为器件名称，规格型号，封装
                        TempStr = range.Text.ToString();
                        UpdateSheet.Cells[i - 998, k] = TempStr;
                        BomToExcelSheet.Cells[i, k] = "";
                    }
                }
                
                //for (int i = 1000; i < 1500; i++)
                //{
                //    range = BomToExcelSheet.Rows[i, this.missing];
                //    range.Delete(Excel.XlDirection.xlDown);
                //}


                UpdateSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
                UpdateSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18" + textBoxProduct.Text + textBoxChinaName.Text + "元件清单更改记录";
                UpdateSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" + comboBoxBomRev.Text;// textBoxBomRev.Text;
                //自定义页脚
                UpdateSheet.PageSetup.LeftFooter = @"&""微软雅黑,常规""日期:" + dateTimePicker1.Text;
                UpdateSheet.PageSetup.CenterFooter = @"&""微软雅黑,常规""第&P页/共&N页";
                UpdateSheet.PageSetup.RightFooter = "";

                ProStatus.Text = "已经处理完替换工作";
                label1.Text = "";
                label2.Text = "";
                label3.Text = "";
                comboBox1.Items.Clear();
                comboBox2.Items.Clear();
                comboBox3.Items.Clear();
                FindList.Clear();
                ProCount = 0;
                
                //完成后那个按键不可用
                buttonAdvancedStatus.Enabled = false;
                //整理不可用
                button7.Enabled = false;

                //一定要注意，这是一个全局变量
                rowcount = 0;

                //if (LibFlag)//库文件不用清除
                //Lib_List.Clear();             
                buttonAdvancedStatus.Text = "完成";
                button7.Text = "整理";
                if (comboBox4.Text=="总表")
                FindReplace();
                MessageBox.Show("替换完成!"); ;//替换完成
            }
        
        }

         //处理料单替换工作  点击跳过或下一步
        private void buttonAdvancedStatus_Click(object sender, EventArgs e)
        {
            ReplacePro("替换");
        }

        //在处理完总表整理后进行分表的处理
        public void FindReplace()
        {
            MessageBox.Show("分表自动替换正在开发中。。。");    
        }


        //打开多张表
        public void OpenBom()
        {
            //-------------对话框----------------------------
            string TempPath = "";
            OpenFileDialog openExcel = new OpenFileDialog();    //实例化打开对话框对象
            openExcel.Filter = "bom文件|*.bom|文本文件|*.txt";  //设置打开文件筛选器
            openExcel.Multiselect = true;                       //设置打开对话框中不能多选

            ProStatus.Text = "正在处理,请稍后...";
            if (openExcel.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            //-------------对话框结束--------------------------

            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int BomNum = 0,CopyBom=0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "多表配置样板")
                {
                    BomNum = i;
                }
                if (workbook.Worksheets[i].Name == "多表配置")
                {
                    CopyBom = i;
                }
            }

            //更改上一版本为副本
            if (CopyBom != 0)
            {
                Excel.Worksheet CopyBomSheet = workbook.Worksheets[CopyBom];//要操作的表的索引。
                CopyBomSheet.Name = CopyBomSheet.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
            }

            //PCB输出样板存副本
            Excel.Worksheet BomConfigSheetCopy = workbook.Worksheets[BomNum];//要操作的表的索引。
            //复制一个表
            object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            BomConfigSheetCopy.Copy(Missing, BomConfigSheetCopy);
            //对新建的PCB输出样板进行操作
            Excel.Worksheet BomConfigSheet = workbook.Worksheets[BomNum + 1];//要操作的表的索引。
            BomConfigSheet.Name = "多表配置";
            ProStatus.Text = "正在处理" + BomConfigSheet.Name + "表，请稍后...";

            //存入打开文件个数
            BomNumCount = openExcel.FileNames.Length;
            for (int i = 0; i < openExcel.FileNames.Length; i++)
            {
                BomFilePath[i] = openExcel.FileNames[i];             //目录及文件名 存到全局变量里
                TempPath = openExcel.FileNames[i];                   //目录及文件名
                ProStatus.Text = "已选择bom文件！等待输入参数进行转换。";   //显示状态                    
                //获取文件名
                TextBoxBomName.Text = TempPath.Substring(TempPath.LastIndexOf("\\") + 1, TempPath.LastIndexOf(".") - (TempPath.LastIndexOf("\\") + 1)); //获取文件名
                BomFileName[i] = TextBoxBomName.Text;//后缀 确认板本
                //获取文件扩展名
                if (TempPath.Substring(TempPath.LastIndexOf(".") + 1, TempPath.Length - TempPath.LastIndexOf(".") - 1) == "txt")//获取文件扩展名
                { comboBoxSoftRev.Text = "ad10"; }
                else
                { comboBoxSoftRev.Text = "protel99se"; }
                BomConfigSheet.Cells[i + 2, 1] = i + 1;         //序号
                BomConfigSheet.Cells[i + 2, 2] = "L1305(样板)";       //项目名称
                BomConfigSheet.Cells[i + 2, 3] = DateTime.Now.ToString("yyyy-MM-dd");       //打印日期
                //获取BOM文件名 3列
                BomConfigSheet.Cells[i + 2, 4] = TextBoxBomName.Text; // TempPath.Substring(TempPath.LastIndexOf("\\") + 1, TempPath.LastIndexOf(".") - (TempPath.LastIndexOf("\\") + 1));
                BomConfigSheet.Cells[i + 2, 5] = "机车信号主机板(样板)";     //中文名
                BomConfigSheet.Cells[i + 2, 6] = TextBoxBomName.Text;    //PCB板名
                BomConfigSheet.Cells[i + 2, 7] = "V10(样板)";     //PCB版本
                BomConfigSheet.Cells[i + 2, 8] = "150*100";     //PCB尺寸
                BomConfigSheet.Cells[i + 2, 9] = DateTime.Now.ToString("yyyy-MM-dd");   //PCB板内日期
                BomConfigSheet.Cells[i + 2, 10] = "2";     //板层
                BomConfigSheet.Cells[i + 2, 11] = "10";     //下单数量
                BomConfigSheet.Cells[i + 2, 12] = "1.6";     //厚度
                BomConfigSheet.Cells[i + 2, 13] = "无铅喷锡";     //加工工艺
                BomConfigSheet.Cells[i + 2, 14] = DateTime.Now.ToString("yyyy-MM-dd");    //加工日期
                BomConfigSheet.Cells[i + 2, 15] = openExcel.FileNames[i];                 //目录及文件名 路径 
                BomConfigSheet.Cells[i + 2, 16] = comboBoxSoftRev.Text;                   //软件版本
            }
                //防止没有文件乱执行
                // 合并总表功能有作用
               // button4.Enabled = true;  
            //保存配置有用了
            button22.Enabled = true;
        }

        //打开多张BOM
        private void button3_Click(object sender, EventArgs e)
        {
            OpenBom();

        }


        //总表封面
        public void AllbomCover() 
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int AllBom = 0,TempAllbomCover = 0;
            string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                tabname[i - 1] = workbook.Worksheets[i].Name;       //存工作簿
                if (workbook.Worksheets[i].Name == "总表封面样板")
                {
                    AllBom = i;
                }
                if (workbook.Worksheets[i].Name == "总表封面")
                {
                    TempAllbomCover = i;
                }
            }
            if (TempAllbomCover != 0)
            {
                Excel.Worksheet DeleteAllBomSheet = workbook.Worksheets[TempAllbomCover];//要操作的表的索引。
                DeleteAllBomSheet.Name = DeleteAllBomSheet.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
            }
            Excel.Worksheet AllBomSheetCopy = workbook.Worksheets[AllBom];//要操作的表的索引。
            //复制一个总表样板
            object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            AllBomSheetCopy.Copy(Missing, AllBomSheetCopy);
            //对新建的PCB输出样板进行操作
            Excel.Worksheet AllBomSheet = workbook.Worksheets[AllBom + 1];//要操作的表的索引。
            AllBomSheet.Name = "总表封面";
            Excel.Range range;
            range = AllBomSheet.Range[AllBomSheet.Cells[10, 3], AllBomSheet.Cells[13, 22]]; //项目名称
            range.ClearContents(); //先把Range内容清除，合并才不会出错
            range.MergeCells = true;
            range.Value2 =  textBoxAllTitle.Text + "汇总表";

            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
            range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
            range.Name = "微软雅黑";
            range.Font.FontStyle = "常规";;
            range.Font.Size = 36;


            range = AllBomSheet.Range[AllBomSheet.Cells[20, 10], AllBomSheet.Cells[21, 16]]; //项目名称
            range.ClearContents(); //先把Range内容清除，合并才不会出错
            range.MergeCells = true;
            range.Value2 = "文件共     页";

            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
            range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
            range.Name = "微软雅黑";
            range.Font.FontStyle = "常规"; ;
            range.Font.Size = 20;


            //自定义页眉
            AllBomSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
            //AllBomSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18" + textBoxAllTitle.Text + "汇总表";
            AllBomSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" + textBoxAllRev.Text;// textBoxBomRev.Text;
            //自定义页脚
            AllBomSheet.PageSetup.LeftFooter = @"编制:" + textBoxcompile.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");
            AllBomSheet.PageSetup.CenterFooter = @"审核:" + textBoxCheck.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");
            AllBomSheet.PageSetup.RightFooter = @"批准:" + textBoxRatify.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");



            ////编制
            //range = AllBomSheet.Range[AllBomSheet.Cells[45, 5], AllBomSheet.Cells[45, 6]]; //项目名称
            //range.ClearContents(); //先把Range内容清除，合并才不会出错
            //range.MergeCells = true;
            //range.Value2 = textBoxcompile.Text;

            ////编制 日期
            //range = AllBomSheet.Range[AllBomSheet.Cells[45, 8], AllBomSheet.Cells[45, 9]]; //项目名称
            //range.ClearContents(); //先把Range内容清除，合并才不会出错
            //range.MergeCells = true;
            //range.Value2 = DateTime.Now.ToString("yyyy-MM-dd"); 

            ////审核
            //range = AllBomSheet.Range[AllBomSheet.Cells[45, 11], AllBomSheet.Cells[45, 12]]; //项目名称
            //range.ClearContents(); //先把Range内容清除，合并才不会出错
            //range.MergeCells = true;
            //range.Value2 = textBoxCheck.Text;

            ////审核 日期
            //range = AllBomSheet.Range[AllBomSheet.Cells[45, 14], AllBomSheet.Cells[45, 15]]; //项目名称
            //range.ClearContents(); //先把Range内容清除，合并才不会出错
            //range.MergeCells = true;
            //range.Value2 = DateTime.Now.ToString("yyyy-MM-dd"); 

            ////批准
            //range = AllBomSheet.Range[AllBomSheet.Cells[45, 17], AllBomSheet.Cells[45, 18]]; //项目名称
            //range.ClearContents(); //先把Range内容清除，合并才不会出错
            //range.MergeCells = true;
            //range.Value2 = textBoxRatify.Text;

            ////批准 日期
            //range = AllBomSheet.Range[AllBomSheet.Cells[45, 20], AllBomSheet.Cells[45, 21]]; //项目名称
            //range.ClearContents(); //先把Range内容清除，合并才不会出错
            //range.MergeCells = true;
            //range.Value2 = DateTime.Now.ToString("yyyy-MM-dd");


            //for (int i = 0; i < OkAllList.Count; i++)
            //{
            //    AllBomSheet.Cells[i + 1, 1] = OkAllList[i];
            //}
 
        }

        //总表内容存到 Addlist去
        public void Addlist()
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int AllBom = 0;//,test=0;
            string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "总表")
                {
                    AllBom = i;
                }
            }
            Excel.Worksheet AllSheet = workbook.Worksheets[AllBom];//要操作的表的索引。
            //Excel.Worksheet testSheet = workbook.Worksheets[test];//要操作的表的索引。
            //ProStatus.Text = "正在处理" + BomConfigSheet.Name + "表，请稍后...";
            Excel.Range range;// = BomConfigSheet.Range[BomConfigSheet.Cells[ 2, 1], BomConfigSheet.Cells[2, 1]];                         //第1列内容为序号 
            string TempStr = "";
            int rowstemp = 1;

            for (int i = 5; i < 20000; i++)
            {
                range = AllSheet.Range[AllSheet.Cells[i, 1], AllSheet.Cells[i, 1]];
                TempStr = range.Text.ToString();
                if (TempStr == "")
                {
                    rowstemp = i - 1;
                    break;
                }
            }
            //进行排一下序AllSheet.Cells[i, 10 + BomNumCount]
            range = AllSheet.Range[AllSheet.Cells[5, 1], AllSheet.Cells[rowstemp, 4]]; //  4 有点问题 改为-> 10 + BomNumCount + 1              
            range.Sort(
             range.Columns[2, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[4, missing], missing, Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[3, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing, missing,
             Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortColumns,
             Microsoft.Office.Interop.Excel.XlSortMethod.xlPinYin,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal);

            //自定义排序
            menfun();
            sortfunv11();

            //存入总表所有内容
            OkAllList.Clear();
            for (int i = 5; i < 20000; i++)
            {
                range = AllSheet.Range[AllSheet.Cells[i, 1], AllSheet.Cells[i, 1]];
                TempStr = range.Text.ToString();
                if (TempStr == "")
                    break;
                
                AllSheet.Cells[i, 1] = i - 4;

                for (int j = 1; j < 5; j++)
                {
                    range = AllSheet.Range[AllSheet.Cells[i, j], AllSheet.Cells[i, j]];
                    TempStr = range.Text.ToString();
                    OkAllList.Add(TempStr);//将读取到的行内容添加到泛型集合中
                }
            }
        }

        //读取替换表
        public void ReaderReplaceList()
        {
            //读取
            string Replace_Line;
            AllReplace_List.Clear();
            //读取退出
            StreamReader ReplaceReader = new StreamReader(ReplacePath, Encoding.Default);  //实例化流读取对象
            while ((Replace_Line = ReplaceReader.ReadLine()) != null)                                           //循环读取文本文件中的每一行
            {
                AllReplace_List.Add(Replace_Line);                                                                 //将读取到的行内容添加到泛型集合中
            }
            ReplaceReader.Close();
            ReplaceReader.Dispose();
        }

        //替换内容
        public void Replacebom(string sheets)
        {
            string TempStr = "", name, part, foot;
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int BomNum = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == sheets)
                {
                    BomNum = i;
                }
            }
            Excel.Worksheet ReplaceSheet = workbook.Worksheets[BomNum];//要操作的表的索引。
            Excel.Range range;

            for (int TempRow = 5; TempRow < 20000; TempRow++)
            {
                range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 1], ReplaceSheet.Cells[TempRow, 1]];
                TempStr = range.Text.ToString();
                if (TempStr == "")
                {
                    break;
                }
                range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 2], ReplaceSheet.Cells[TempRow, 2]];
                name = range.Text.ToString();
                range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 3], ReplaceSheet.Cells[TempRow, 3]];
                part = range.Text.ToString();
                range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 4], ReplaceSheet.Cells[TempRow, 4]];
                foot = range.Text.ToString();

                ReplaceSheet.Cells[TempRow, 10 + BomNumCount] = "";
                ReplaceSheet.Cells[TempRow, 5] = "";

                for (int i = 0; i < AllReplace_List.Count-1;)
                {
                    if ((name == AllReplace_List[i + 1]) && (part == AllReplace_List[i + 3]) && (foot == AllReplace_List[i + 5]))
                    {
                        //ReplaceSheet.Cells[TempRow, 10 + BomNumCount] = AllReplace_List[i + 0]; //备注一下替换表的行号

                        ReplaceSheet.Cells[TempRow, 5] = "替; " + AllReplace_List[i + 0]; //备注一下替换表的行号

                        if (AllReplace_List[i + 2] != "保持不变")
                        {
                            ReplaceSheet.Cells[TempRow, 2] = AllReplace_List[i + 2];
                            range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 2], ReplaceSheet.Cells[TempRow, 2]];
                            range.Interior.ColorIndex = 3;  
                        }
                        if (AllReplace_List[i + 4] != "保持不变")
                        {
                            ReplaceSheet.Cells[TempRow, 3] = AllReplace_List[i + 4];
                            range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 3], ReplaceSheet.Cells[TempRow, 3]];
                            range.Interior.ColorIndex = 3;  
                        }
                        if (AllReplace_List[i + 6] != "保持不变")
                        {
                            ReplaceSheet.Cells[TempRow, 4] = AllReplace_List[i + 6];
                            range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 4], ReplaceSheet.Cells[TempRow, 4]];
                            range.Interior.ColorIndex = 3;   
                        }                      
                        //range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 1], ReplaceSheet.Cells[TempRow, 1]];
                        //range.Interior.ColorIndex = 3;   
                        break;
                    }
                    i = i + 9;
                }
            }
        }

        //  #region 处理合并总表
        private void button4_Click(object sender, EventArgs e)
        {
            //关闭多表合并功能，防止误点
            button4.Enabled = false;
            //多表操作时，单表不能执行
            button2.Enabled = false;
            //清除要查找的替换内容
            FindList.Clear();
            ProCount = 0;
      
            //读取多表总和
            List<string> All_List = new List<string>(); 

            //All_List.Clear();//清除多表的内容

            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int BomNum = 0,AllBom=0;
            string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                tabname[i - 1] = workbook.Worksheets[i].Name;       //存工作簿
                if (workbook.Worksheets[i].Name == "多表配置")
                {
                    BomNum = i;
                }
                if (workbook.Worksheets[i].Name == "总表样板")
                {
                    AllBom = i;
                }
                if (workbook.Worksheets[i].Name == "总表")
                {
                    Excel.Worksheet delallSheet = workbook.Worksheets[i];//要操作的表的索引。
                    delallSheet.Name = delallSheet.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
                }
            }
            Excel.Worksheet BomConfigSheet = workbook.Worksheets[BomNum];//要操作的表的索引。
            ProStatus.Text = "正在处理" + BomConfigSheet.Name + "表，请稍后...";
            Excel.Range range;// = BomConfigSheet.Range[BomConfigSheet.Cells[ 2, 1], BomConfigSheet.Cells[2, 1]];                         //第1列内容为序号 

            //进行单表生成

            if (BomNum!=0)
            {
                for (int i = 0; i < BomNumCount; i++)//BomNumCount
                {
                    range = BomConfigSheet.Range[BomConfigSheet.Cells[i+2, 1], BomConfigSheet.Cells[i+2, 1]];                         //第1列内容为序号        
                    if (range.Text.ToString() != "")
                    {
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 2], BomConfigSheet.Cells[i + 2, 2]]; //项目名称
                        textBoxProduct.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 3], BomConfigSheet.Cells[i + 2, 3]]; //打印日期
                        dateTimePicker1.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 4], BomConfigSheet.Cells[i + 2, 4]]; //BOM文件名
                        TextBoxBomName.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 5], BomConfigSheet.Cells[i + 2, 5]]; //中文名
                        textBoxChinaName.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 6], BomConfigSheet.Cells[i + 2, 6]]; //PCB板名
                        textBoxPCB.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 7], BomConfigSheet.Cells[i + 2, 7]]; //硬件版本
                        comboBoxBomRev.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 8], BomConfigSheet.Cells[i + 2, 8]]; //PCB板尺寸
                        textBoxSize.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 9], BomConfigSheet.Cells[i + 2, 9]]; //PCB板内日期
                        PcbDate.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 10], BomConfigSheet.Cells[i + 2, 10]]; //PCB板层数
                        comboBoxLayer.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 11], BomConfigSheet.Cells[i + 2, 11]]; //PCB板下单数量
                        textBoxPcbNum.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 12], BomConfigSheet.Cells[i + 2, 12]]; //PCB板厚度
                        comboBoxThickness.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 15], BomConfigSheet.Cells[i + 2, 15]]; //路径
                        BomPath.Text = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 16], BomConfigSheet.Cells[i + 2, 16]]; //PCB软件版本
                        comboBoxSoftRev.Text = range.Text.ToString();
                        bomProExcel();
                    }  
                }

                Excel.Worksheet AllBomSheetCopy = workbook.Worksheets[AllBom];//要操作的表的索引。
                //复制一个总表样板
                object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
                AllBomSheetCopy.Copy(Missing, AllBomSheetCopy);
                //对新建的PCB输出样板进行操作
                Excel.Worksheet AllBomSheet = workbook.Worksheets[AllBom + 1];//要操作的表的索引。
                AllBomSheet.Name = "总表";
                ProStatus.Text = "正在处理" + BomConfigSheet.Name + "表，请稍后...";



                //把所有分表的内容统一汇总到 All_List 列表中

                int TempExcelRow = 5,IDnum = 1; //第5行开始
                for (int table = 0; table < BomNumCount; table++)
                {
                    for (int i = 1; i <= workbook.Worksheets.Count; i++)
                    {
                        if (workbook.Worksheets[i].Name == BomFileName[table])
                        {
                            // BomNum = i;
                            BomConfigSheet = workbook.Worksheets[i];//要操作的表的索引。
                            //range = BomConfigSheet.Range[BomConfigSheet.Cells[i + 2, 1], BomConfigSheet.Cells[i + 2, 1]];
                            //存储字符的个数
                            string TempStr = "";                                                                                                        //存储读取的内容
                            //把所有单表的器件写入All_List进行统一处理
                            int  tid = 0;
                            for (int TempRow = 3; TempRow < 10000; TempRow++)//遍历数据集中表的行数
                            {
                                //读取第3行第一列为序号
                                range = BomConfigSheet.Range[BomConfigSheet.Cells[TempRow, 1], BomConfigSheet.Cells[TempRow, 1]];                         //第1列内容为序号
                                tid = TempRow - 2;
                                if (range.Text.ToString() != "")//(tid.ToString()) == (range.Text.ToString())
                                {
                                    //AllBomSheet.Cells[TempExcelRow, 1] = Convert.ToString(IDnum);
                                    range = BomConfigSheet.Range[BomConfigSheet.Cells[TempRow, 3], BomConfigSheet.Cells[TempRow, 3]];   //第3-5列内容为器件名称，规格型号，封装
                                    TempStr = range.Text.ToString();
                                    All_List.Add(TempStr); 
                                    //AllBomSheet.Cells[TempExcelRow, 2] = TempStr;
                                    range = BomConfigSheet.Range[BomConfigSheet.Cells[TempRow, 4], BomConfigSheet.Cells[TempRow, 4]];   //第3-5列内容为器件名称，规格型号，封装
                                    TempStr = range.Text.ToString();
                                    All_List.Add(TempStr); 
                                    //AllBomSheet.Cells[TempExcelRow, 3] = TempStr;
                                    range = BomConfigSheet.Range[BomConfigSheet.Cells[TempRow, 5], BomConfigSheet.Cells[TempRow, 5]];   //第3-5列内容为器件名称，规格型号，封装
                                    TempStr = range.Text.ToString();
                                    All_List.Add(TempStr);
                                    //AllBomSheet.Cells[TempExcelRow, 4] = TempStr;
                                    TempExcelRow++; IDnum++;

                                }
                                else
                                {
                                    break;
                                }
                            }
                        }//处理单表添加
                    } //查表FOR                   
                } //表处理完成
                ////MessageBox.Show("多表处理完成！");


                //更改列宽，重新分配打开多个表的列宽
                //StartColumn 开始列为5，
                //EndColumn = 结束列为5  + BomNumCount + 6 
                //TabNum = 表的结束列 BomNumCount + 6;
                int DelTab, addcol;// = 22 - BomNumCount; 
                int StartColumn = 5, EndColumn = BomNumCount + 6 + 5, TabNum = BomNumCount + 6;
                double TabWidth = (119 / (BomNumCount + 6)) + 0.6;
                if (TabWidth < 1)
                {
                    TabWidth = 1;
                }

                if (BomNumCount < 23)
                {
                    DelTab = 22 - BomNumCount;
                    while (DelTab != 0)
                    {
                        range = AllBomSheet.Columns["G:G", System.Type.Missing];
                        range.Columns.Delete();
                        DelTab--;
                    }
                }
                else
                {
                    addcol = BomNumCount - 22;
                    while (addcol != 0)
                    {
                        range = AllBomSheet.Columns["G:G", System.Type.Missing];
                        range.Insert(Excel.XlDirection.xlDown, missing);
                        addcol--;
                    }
                }

                while (StartColumn != EndColumn)
                {
                    range = AllBomSheet.Columns[GetColumnName(StartColumn) + ":" + GetColumnName(StartColumn), System.Type.Missing];
                    range.ColumnWidth = TabWidth;
                    StartColumn++;
                }



                string FindTempPartNameContent = "", FindTempPartTypeContent = "", FindTempPartFootContent = "";
                string FindTempPartTypeContentCOM = "", FindTempPartFootContentCOM = "";
                //int tempLT = 0;
                bool brB = false;
                TempExcelRow = 5;
                IDnum = 1; //第5行开始

                FindList.Clear();
                ProCount = 0;
                OkAllList.Clear();


                //总表第5行的内容要特殊处理一下
                //第5行的内容
                AllBomSheet.Cells[TempExcelRow, 1] = Convert.ToString(IDnum);
                AllBomSheet.Cells[TempExcelRow, 2] = All_List[0];
                AllBomSheet.Cells[TempExcelRow, 3] = All_List[1];
                AllBomSheet.Cells[TempExcelRow, 4] = All_List[2];

                OkAllList.Add(Convert.ToString(IDnum));
                OkAllList.Add(FindTempPartNameContent);
                OkAllList.Add(FindTempPartTypeContent);
                OkAllList.Add(FindTempPartFootContent);

                //表名的表头对应的值
                for (int f = 0; f < BomNumCount; f++)
                {
                    AllBomSheet.Cells[TempExcelRow, 7 + f] = @"=SUMIFS(" + BomFileName[f] + "!F:F," + BomFileName[f] + "!D:D,总表!C" + TempExcelRow + "," + BomFileName[f] + "!E:E,总表!D" + TempExcelRow + ")";
                }
                string K1 = "", K2 = "=", K4 = "=";
                for (int k = 7; k < 7 + BomNumCount; k++)
                {
                    K1 = GetColumnName(k);
                    if (k == (7 + BomNumCount - 1))
                    {
                        K2 = K2 + K1 + "$2*" + K1 + TempExcelRow;
                        K4 = K4 + K1 + "$3*" + K1 + TempExcelRow;
                    }
                    else
                    {
                        K2 = K2 + K1 + "$2*" + K1 + TempExcelRow + "+";
                        K4 = K4 + K1 + "$3*" + K1 + TempExcelRow + "+";
                    }
                }
                AllBomSheet.Cells[TempExcelRow, 7 + BomNumCount] = @K2;
                AllBomSheet.Cells[TempExcelRow, 7 + BomNumCount + 1] = @K4;
                TempExcelRow++; IDnum++;


                //总表填入已筛选过重重项的料单
                int lenght = All_List.Count / 3;
                for (int i = 1; i < lenght; i++)
                {                      
                        FindTempPartNameContent = All_List[i * 3 + 0];
                        FindTempPartTypeContent = All_List[i * 3 + 1];
                        FindTempPartFootContent = All_List[i * 3 + 2];
                        for (int l = 0; l < i; l++)
                        {
                            FindTempPartTypeContentCOM = All_List[l * 3 + 1];
                            FindTempPartFootContentCOM = All_List[l * 3 + 2];
                            if ((FindTempPartTypeContentCOM == FindTempPartTypeContent) && (FindTempPartFootContentCOM == FindTempPartFootContent))
                            {
                                brB = true;
                                break;
                            }

                        }

                        if (brB)
                        {
                            brB = false;
                        }
                        else
                        {
                            AllBomSheet.Cells[TempExcelRow, 1] = Convert.ToString(IDnum);
                            AllBomSheet.Cells[TempExcelRow, 2] = FindTempPartNameContent;
                            AllBomSheet.Cells[TempExcelRow, 3] = FindTempPartTypeContent;
                            AllBomSheet.Cells[TempExcelRow, 4] = FindTempPartFootContent;
                            
                            //辅助整理时使用
                            OkAllList.Add(Convert.ToString(IDnum));
                            OkAllList.Add(FindTempPartNameContent);
                            OkAllList.Add(FindTempPartTypeContent);
                            OkAllList.Add(FindTempPartFootContent);

                            //存入查找不到的内容待整理
                            if (FindTempPartNameContent == "ERROR(NC)")
                            {
                                FindList.Add(TempExcelRow.ToString());//Convert.ToString(TempExcelRow));              //记录当前行号
                                FindList.Add(FindTempPartNameContent);
                                FindList.Add(FindTempPartTypeContent);              //记录器件规格型号
                                FindList.Add(FindTempPartFootContent);                                
                            }

                            //表名的表头对应的值
                            for (int f = 0; f < BomNumCount; f++)
                            {
                                AllBomSheet.Cells[TempExcelRow, 7 + f] = @"=SUMIFS(" + BomFileName[f] + "!F:F," + BomFileName[f] + "!D:D,总表!C" + TempExcelRow + "," + BomFileName[f] + "!E:E,总表!D" + TempExcelRow + ")";
                            }

                            K1 = ""; K2 = "="; K4 = "=";
                            for (int k = 7; k < 7 + BomNumCount; k++)
                            {
                                K1 = GetColumnName(k);
                                if (k == (7 + BomNumCount - 1))
                                {
                                    K2 = K2 + K1 + "$2*" + K1 + TempExcelRow;
                                    K4 = K4 + K1 + "$3*" + K1 + TempExcelRow;
                                }
                                else
                                {
                                    K2 = K2 + K1 + "$2*" + K1 + TempExcelRow + "+";
                                    K4 = K4 + K1 + "$3*" + K1 + TempExcelRow + "+";
                                }
                            }
                            AllBomSheet.Cells[TempExcelRow, 7 + BomNumCount] = @K2;
                            AllBomSheet.Cells[TempExcelRow, 7 + BomNumCount + 1] = @K4;
                            TempExcelRow++; IDnum++; brB = false;
                        }
                        
               }

                //表名的表头
                //for (int i = 0; i < BomNumCount; i++)
                //{
                //    AllBomSheet.Cells[1, 7 + i ] = BomFileName[i];
                //    AllBomSheet.Cells[4, 7 + i ] = BomFileName[i];               
                //}

                //自定义页眉
                AllBomSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
                AllBomSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18" + textBoxAllTitle.Text  + "汇总表";
                AllBomSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" +  textBoxAllRev.Text;// textBoxBomRev.Text;
                //自定义页脚
                AllBomSheet.PageSetup.LeftFooter = @"▲代表关键器件";
                AllBomSheet.PageSetup.CenterFooter = @"&""微软雅黑,常规""第&P页/共&N页";
                AllBomSheet.PageSetup.RightFooter = "";
                //textBoxAllTitle.Text;
                //textBoxAllRev.Text;
                //textBoxcompile.Text;
                //textBoxCheck.Text;
                //textBoxRatify.Text;


                
                //给分表加索引
                int excelrow = 3;
                string TempStr1 = "123";
                Excel.Worksheet SingleSheet;
                for (int s = 0; s < BomNumCount; s++)
                {
                    AllBomSheet.Cells[1, 7 + s] = BomFileName[s];
                    AllBomSheet.Cells[4, 7 + s] = BomFileName[s];

                    for (int n = 1; n <= workbook.Worksheets.Count; n++)
                    {
                        if (workbook.Worksheets[n].Name == BomFileName[s])
                        {
                            SingleSheet = workbook.Worksheets[n];//要操作的表的索引。
                            SingleSheet.Cells[2, 8] = "=总表!"+ GetColumnName(7 + s) + "3";
                            SingleSheet.Cells[1, 10] = "总表索引";
                            while (true)
                            {
                                range = SingleSheet.Range[SingleSheet.Cells[excelrow, 1], SingleSheet.Cells[excelrow, 1]];
                                TempStr1 = range.Text.ToString();
                                if (TempStr1 != "")
                                {
                                    SingleSheet.Cells[excelrow, 10] = @"=SUMIFS(总表!" + GetColumnName(7 + s) + ":" + GetColumnName(7 + s) + ",总表!C:C," + SingleSheet.Name + "!D" + excelrow + ",总表!D:D," + SingleSheet.Name + "!E" + excelrow;
                                    SingleSheet.Cells[excelrow, 8] = "=H$2*F" + excelrow;
                                    excelrow++;
                                }
                                else
                                {
                                    excelrow = 3;
                                    break;
                                }
                            }               
                        }
                    }
                }

                //总表封面
                AllbomCover();

                //默认情况不输出
                buttonALLPCPOUT.Enabled = true;
                //整理的那个表示“成功”的按键
                buttonAdvancedStatus.Enabled = true;
                //整理按钮
                button7.Enabled = true;
                //多表合并重新可用
                //button4.Enabled = true;
                //辅助整理打开
                button11.Enabled = true;
                //辅助单表查找替换
                //button12.Enabled = true;
                //保存分表到数据库
                button24.Enabled = true;

                comboBox4.Items.Clear();
                comboBox4.Text = "总表";

                //现在查出问题了，下面这一行可以不用加了
                //把总表的所有内容存起来
                Addlist();
                //读取替换表内容
                ReaderReplaceList();
                //替换总表内容
                Replacebom("总表");



                //辅助执行一次，才方法二次整理料单
               //fuzhu();
                ProStatus.Text = "多表转换已完成。";
                //只有保存了配置并生成了表才能输出
                button8.Enabled = true;
                
                MessageBox.Show("多表处理完成！");
            }
        }

     

        /// <summary>
        /// 设置列宽
        /// </summary>
        /// <param name="startColumn">起始列</param>
        /// <param name="endColumn">结束列</param>
        /// <param name="width"></param>
        //public void SetColumnWidth(int startColumn, int endColumn, int width)
        //{
        //    string strStartColumn = GetColumnName(startColumn);
        //    string strEndColumn = GetColumnName(endColumn);
        //    //获取当前正在使用的工作表
        //    Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet;
        //    Excel.Range range = (Excel.Range)worksheet.Columns[strStartColumn + ":" + strEndColumn, System.Type.Missing];
        //    range.ColumnWidth = width;
        //}
        //设置列宽成功
        //Excel.Range range1 = AllBomSheet.Columns["E:E", System.Type.Missing];
        //range1.ColumnWidth = 50;


        private void button5_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("已经将\"器件库.xlsx\"工作表中的数据存到了一个字符串上。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            int P_int_Count = 0;//记录正在读取的行数
            string P_str_Line, P_str_Content = "";//记录读取行的内容及遍历到的内容 

            /**************读取要转换的BOM文件到P_str_List中*********/
            List<string> P_str_List = new List<string>();   //存储读取的所有内容
            StreamReader SReader = new StreamReader(BomPath.Text, Encoding.Default);//实例化流读取对象
            while ((P_str_Line = SReader.ReadLine()) != null)       //循环读取文本文件中的每一行
            {
                P_str_Line = P_str_Line.ToUpper();                  //转换为大写字符
                P_str_List.Add(P_str_Line);                         //将读取到的行内容添加到泛型集合中
                P_int_Count++;                                      //使当前读取行数加1
            }

            /*可配置excel单元格列的位置*/
            int txtpartname = 3;                 //器件的名称
            int txtparttypecolumn = 4;          //元件参数 列位置
            int txtfootprintcolumn = 5;         //元件封装列位置
            int txtusedcolumn = 6;              //元件用量 列位置
            int txtdesignatorcolumn = 7;        //元件标号 列位置
            int txtlibrefcolumn = 10;             //原里图名称

            int[] Column = new int[10];
            int tempcount = 0, tempcjj = 0;
            P_str_Content = P_str_List[0];
            //string as1="";
            bool fs = false;
            for (int f = 0; f < P_str_Content.Length; )
            {
                if (P_str_Content.Substring(f, 1) == "\t")
                {
                    switch (P_str_Content.Substring(tempcjj, f - tempcjj))
                    {
                        case "COMMENT":     //器件规格型号
                            Column[tempcount] = txtparttypecolumn; //
                            break;
                        case "DESCRIPTION": //描述
                            Column[tempcount] = txtpartname;// 
                            break;
                        case "DESIGNATOR":  //编号
                            Column[tempcount] = txtdesignatorcolumn; //
                            break;
                        case "FOOTPRINT":   //封装
                            Column[tempcount] = txtfootprintcolumn; //;
                            break;
                        case "LIBREF":      //库名称
                            Column[tempcount] = txtlibrefcolumn;//
                            break;
                        case "QUANTITY":    //数量
                            Column[tempcount] = txtusedcolumn;//
                            break;
                        default:
                            fs = true;
                            break;
                    }
                    if (fs)
                    {
                        fs = false;
                    }
                    else
                    {
                        tempcjj = ++f;
                        tempcount++;
                        fs = false;
                    }
                }
                else
                {
                    f++;
                    if (f == P_str_Content.Length)
                    {                           
                        switch (P_str_Content.Substring(tempcjj, f - tempcjj))
                        {
                            case "COMMENT": //器件规格型号
                                Column[tempcount] = txtparttypecolumn; //
                                break;
                            case "DESCRIPTION": //描述
                                Column[tempcount] = txtpartname;// 
                                break;
                            case "DESIGNATOR"://编号
                                Column[tempcount] = txtdesignatorcolumn; //
                                break;
                            case "FOOTPRINT": ;//封装
                                Column[tempcount] = txtfootprintcolumn; //;
                                break;
                            case "LIBREF"://库名称
                                Column[tempcount] = txtlibrefcolumn;//
                                break;
                            case "QUANTITY"://数量
                                Column[tempcount] = txtusedcolumn;//
                                break;
                            default:
                                break;
                        }
                        f = f+2;
                    }
                }
            }

            /*处理两个工作表分别为：料单样板、器件库*/
            //Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            //int sheetnum = 0, PartLib = 0;
            //string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            //for (int i = 1; i <= workbook.Worksheets.Count; i++)
            //{
            //    tabname[i - 1] = workbook.Worksheets[i].Name + " ";       //存工作簿
            //    //if (workbook.Worksheets[i].Name == "料单样板")
            //    //{
            //    //    sheetnum = i;
            //    //}
            //    if (workbook.Worksheets[i].Name == "器件库")
            //    {
            //        PartLib = i;
            //    }
            //}

            //////料单样板存副本
            ////Excel.Worksheet BomToExcelSheetCopy = workbook.Worksheets[sheetnum];//要操作的表的索引。
            //////复制一个表
            ////object Missing = System.Reflection.Missing.Value;                   //获取缺少的object类型值
            ////BomToExcelSheetCopy.Copy(Missing, BomToExcelSheetCopy);

            //////料单样板
            ////Excel.Worksheet BomToExcelSheet = workbook.Worksheets[sheetnum + 1];//要操作的表的索引。
            ////BomToExcelSheet.Name = TextBoxBomName.Text;

            //////ProStatus.Text = string.Empty;
            ////ProStatus.Text = "正在处理" + BomToExcelSheet.Name + "表，请稍后...";
            //////ProStatus.BackColor = ;
            ////器件库
            //Excel.Worksheet PartLibSheet = workbook.Worksheets[PartLib];    //要操作的表的索引为器件库。
            //Excel.Range range;

            //int Lib_Count = 0;                                                                                                          //存储字符的个数
            //string TempStr = "";                                                                                                        //存储读取的内容
            ////把器件库中所有器件写入进行处理
            //for (int TempRow = 1; TempRow < 10000; TempRow++)//遍历数据集中表的行数
            //{
            //    range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, 1], PartLibSheet.Cells[TempRow, 1]];                         //第1列内容为序号
            //    TempStr = range.Text.ToString();
            //    if (TempStr == (TempRow.ToString()))
            //    {
            //        for (int TempColumn = 1; TempColumn < 5; TempColumn++)                                                          //遍历数据集中表的列数
            //        {
            //            TempStr = "";
            //            range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, TempColumn], PartLibSheet.Cells[TempRow, TempColumn]];   //第2-4列内容为器件名称，规格型号，封装
            //            TempStr = range.Text.ToString();
            //            TempStr = TempStr.ToUpper(); //所有的转换为大写的内容
            //            Lib_List.Add(TempStr);//将读取到的行内容添加到泛型集合中
            //            Lib_Count++;//使当前读取行数加1
            //        }
            //    }
            //    else
            //    {
            //        break;
            //    }
            //}
      
            MessageBox.Show("读取完成");
        }

        //获取列的英文标号
        public string GetColumnName(int number)
        {
            int h, l;
            h = number / 26;
            l = number % 26;
            if (l == 0)
            {
                h -= 1;
                l = 26;
            }
            string s = GetLetter(h) + GetLetter(l);
            return s;
        }

        //数字行列转为字母，只参转26以下的。
        private string GetLetter(int number)
        {
            switch (number)
            {
                case 1:
                    return "A";
                case 2:
                    return "B";
                case 3:
                    return "C";
                case 4:
                    return "D";
                case 5:
                    return "E";
                case 6:
                    return "F";
                case 7:
                    return "G";
                case 8:
                    return "H";
                case 9:
                    return "I";
                case 10:
                    return "J";
                case 11:
                    return "K";
                case 12:
                    return "L";
                case 13:
                    return "M";
                case 14:
                    return "N";
                case 15:
                    return "O";
                case 16:
                    return "P";
                case 17:
                    return "Q";
                case 18:
                    return "R";
                case 19:
                    return "S";
                case 20:
                    return "T";
                case 21:
                    return "U";
                case 22:
                    return "V";
                case 23:
                    return "W";
                case 24:
                    return "X";
                case 25:
                    return "Y";
                case 26:
                    return "Z";
                default:
                    return "";
            }
        }

        //单板PCB输出
        private void button6_Click(object sender, EventArgs e)
        {
            //AllbomCover();
            PcbOutFlag = true;
            PcbOut();
            buttonPCBOUT.Enabled = false;
        }

        //多板PCB输出
        private void buttonALLPCPOUT_Click(object sender, EventArgs e)
        {
            PcbOutFlag = false;
            PcbOut();
            buttonALLPCPOUT.Enabled = false;
        }

        //单击出现下拉菜单
        private void comboBox4_Click(object sender, EventArgs e)
        {
            //comboBox4.Text = "你已经单击过";
            /*处理两个工作表分别为：料单样板、器件库*/
           // comboBox4.Items.Clear();
           // Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
           //// int sheetnum = 0, PartLib = 0;
           // string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
           // for (int i = 1; i <= workbook.Worksheets.Count; i++)
           // {
           //     comboBox4.Items.Add(workbook.Worksheets[i].Name);
           // }
        }


        // File.Copy(源文件地址,目标地址, true（为true是覆盖同名文件）); 
        /// <summary>
        /// 从一个目录将其内容移动到另一目录
        /// </summary>
        /// <param name="p">源目录</param>
        /// <param name="p_2">目的目录</param>
        private void MoveFolderTo(string p, string p_2)
        {
            //检查是否存在目的目录
            if (!Directory.Exists(p_2))
                Directory.CreateDirectory(p_2);
            //先来移动文件
            DirectoryInfo info = new DirectoryInfo(p);
            FileInfo[] files = info.GetFiles();
            foreach (FileInfo file in files)
            {
                //File.Copy(param name="p“,Path.Combine(p_2, file.Name）, true（为true是覆盖同名文件）); //复制文件
            }
        }

        //-------------------输出处理模块-------------------------------------------
        //读取分表的内容到SingleBomList中
        public void ReadSingleBomToList(string sheetsname)
        {

            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int ProBom = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == sheetsname)
                {
                    ProBom = i;
                }
            }
            Excel.Worksheet InSheet = workbook.Worksheets[ProBom];
            Excel.Range range;

            string TempStr;
            //存储读取库中的内容
            //把器件库中所有器件写入Lib_List进行处理
            
            SingleBomList.Clear();

            for (int TempRow = 3; TempRow < 100000; TempRow++)//遍历数据集中表的行数
            {
                range = InSheet.Range[InSheet.Cells[TempRow, 1], InSheet.Cells[TempRow, 1]];                         //第1列内容为序号
                TempStr = range.Text.ToString();
                if (TempStr != "")
                {
                    for (int TempColumn = 1; TempColumn < 10; TempColumn++)                                                          //遍历数据集中表的列数
                    {
                        range = InSheet.Range[InSheet.Cells[TempRow, TempColumn], InSheet.Cells[TempRow, TempColumn]];
                        TempStr = range.Text.ToString();
                        TempStr = TempStr.ToUpper(); //所有的转换为大写的内容
                        if (TempStr=="")
                        {
                            TempStr = "nc删除";
                        }
                        SingleBomList.Add(TempStr);                      
                    }
                }
                else
                {
                    break;
                }
            }
        }
        
        //汇总表输出
        public void CollectOut(string filename)
        {

            //读取多表总和
           // List<string> All_List = new List<string>();

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//实例化Excel对象
            object missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            //打开指定的Excel文件
            Microsoft.Office.Interop.Excel.Workbook workbook = excel.Application.Workbooks.Open(@filename, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            workbook.Application.DisplayAlerts = false;


            int AllBom = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "总表样板")
                {
                    AllBom = i;
                }
            }

            //Excel.Worksheet AllBomSheetCopy = workbook.Worksheets[AllBom];//要操作的表的索引。
            //复制一个总表样板
            //object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            //AllBomSheetCopy.Copy(Missing, AllBomSheetCopy);
            //对新建的PCB输出样板进行操作
            //Excel.Worksheet AllBomSheet = workbook.Worksheets[AllBom + 1];//要操作的表的索引。
            Excel.Worksheet AllBomSheet = workbook.Worksheets[AllBom];//要操作的表的索引
            AllBomSheet.Name = "总表";
            Excel.Range range;

            int TempExcelRow = 5,IDnum = 1; //第5行开始


            //存内容到全局变量上
            Addlist();

                        //更改列宽，重新分配打开多个表的列宽
            //StartColumn 开始列为5，
            //EndColumn = 结束列为5  + BomNumCount + 6 
            //TabNum = 表的结束列 BomNumCount + 6;
            int DelTab, addcol;// = 22 - BomNumCount; 
            int StartColumn = 5, EndColumn = BomNumCount + 6 + 5, TabNum = BomNumCount + 6;
            double TabWidth = (119 / (BomNumCount + 6)) + 0.6;
            if (TabWidth < 1)
            {
                TabWidth = 1;
            }

            if (BomNumCount < 23)
            {
                DelTab = 22 - BomNumCount;
                while (DelTab != 0)
                {
                    range = AllBomSheet.Columns["G:G", System.Type.Missing];
                    range.Columns.Delete();
                    DelTab--;
                }
            }
            else
            {
                addcol = BomNumCount - 22;
                while (addcol != 0)
                {
                    range = AllBomSheet.Columns["G:G", System.Type.Missing];
                    range.Insert(Excel.XlDirection.xlDown, missing);
                    addcol--;
                }
            }

            while (StartColumn != EndColumn)
            {
                range = AllBomSheet.Columns[GetColumnName(StartColumn) + ":" + GetColumnName(StartColumn), System.Type.Missing];
                range.ColumnWidth = TabWidth;
                StartColumn++;
            }

            //表名的表头
            for (int i = 0; i < BomNumCount; i++)
            {
                AllBomSheet.Cells[1, 7 + i ] = BomFileName[i];
                AllBomSheet.Cells[4, 7 + i ] = BomFileName[i];               
            }

            //写入所有行
            int count = (OkAllList.Count/4)+5;
            for (int i = 5; i < count ; i++)
			{
                AllBomSheet.Cells[TempExcelRow, 1] = OkAllList[((i-5)*4)+0];
                AllBomSheet.Cells[TempExcelRow, 2] = OkAllList[((i-5)*4)+1];
                AllBomSheet.Cells[TempExcelRow, 3] = OkAllList[((i-5)*4)+2];
                AllBomSheet.Cells[TempExcelRow, 4] = OkAllList[((i-5)*4)+3];

                string K1 = "", K2 = "=", K4 = "=";
                //表名的表头对应的值
                for (int f = 0; f < BomNumCount; f++)
                {
                    AllBomSheet.Cells[TempExcelRow, 7 + f] = @"=SUMIFS(" + BomFileName[f] + "!F:F," + BomFileName[f] + "!D:D,总表!C" + TempExcelRow + "," + BomFileName[f] + "!E:E,总表!D" + TempExcelRow + ")";
                }

                K1 = ""; K2 = "="; K4 = "=";
                for (int k = 7; k < 7 + BomNumCount; k++)
                {
                    K1 = GetColumnName(k);
                    if (k == (7 + BomNumCount - 1))
                    {
                        K2 = K2 + K1 + "$2*" + K1 + TempExcelRow;
                        K4 = K4 + K1 + "$3*" + K1 + TempExcelRow;
                    }
                    else
                    {
                        K2 = K2 + K1 + "$2*" + K1 + TempExcelRow + "+";
                        K4 = K4 + K1 + "$3*" + K1 + TempExcelRow + "+";
                    }
                }
                AllBomSheet.Cells[TempExcelRow, 7 + BomNumCount] = @K2;
                AllBomSheet.Cells[TempExcelRow, 7 + BomNumCount + 1] = @K4;
                TempExcelRow++; IDnum++;			 
			}


            //自定义页眉
            AllBomSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
            AllBomSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18" + textBoxAllTitle.Text + "汇总表";
            AllBomSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" + textBoxAllRev.Text;// textBoxBomRev.Text;
            //自定义页脚
            AllBomSheet.PageSetup.LeftFooter = @"▲代表关键器件";
            AllBomSheet.PageSetup.CenterFooter = @"&""微软雅黑,常规""第&P页/共&N页";
            AllBomSheet.PageSetup.RightFooter = "";
            

            //给分表加索引
            int excelrow = 3;
            string TempStr1 = "123";
            Excel.Worksheet SingleSheet;
            for (int s = 0; s < BomNumCount; s++)
            {
                AllBomSheet.Cells[1, 7 + s] = BomFileName[s];
                AllBomSheet.Cells[4, 7 + s] = BomFileName[s];

                for (int n = 1; n <= workbook.Worksheets.Count; n++)
                {
                    if (workbook.Worksheets[n].Name == BomFileName[s])
                    {
                        SingleSheet = workbook.Worksheets[n];//要操作的表的索引。
                        SingleSheet.Cells[2, 8] = "=总表!" + GetColumnName(7 + s) + "3";
                        while (true)
                        {
                            range = SingleSheet.Range[SingleSheet.Cells[excelrow, 1], SingleSheet.Cells[excelrow, 1]];
                            TempStr1 = range.Text.ToString();
                            if (TempStr1 != "")
                            {
                                SingleSheet.Cells[excelrow, 10] = @"=SUMIFS(总表!" + GetColumnName(7 + s) + ":" + GetColumnName(7 + s) + ",总表!C:C," + SingleSheet.Name + "!D" + excelrow + ",总表!D:D," + SingleSheet.Name + "!E" + excelrow;
                                SingleSheet.Cells[excelrow, 8] = "=H$2*F" + excelrow;
                                excelrow++;
                            }
                            else
                            {
                                excelrow = 3;
                                break;
                            }
                        }
                    }
                }
            }

            workbook.Save();//保存工作表
            workbook.Close(false, missing, missing);//关闭工作表
            

        }

        //PCB文件输出
        public void PcbOut(string filename)
        {

            //1  序号
            int SerialColumn = 1;
            //6  PCB板名
            int PcbNameColumn = 2;
            //7  PCB版本
            //int PcbRevColumn = 2;
            //8  PCB尺寸
            int PcbSizeColumn = 3;
            //9  板内日期
            int PcbDateColumn = 5;
            //11 下单数量
            int PcbNumberColumn = 6;
            //10 板层	
            int PcbLayerColumn = 7;
            //12 厚度
            int PcbThicknessColumn = 8;
            //16 备注： PCB软件版本
            int SoftRevColumn = 9;
            //13 工艺	
            //int PcbCraftColumn = 13;
            //2  项目名称
            //int ProNameColumn = 2;
            //3  打印日期
            //int PrintDateColumn = 3;
            //4  BOM文件名	
            //int BomFileNameColumn = 4;
            //5  BOM中文名
            //int BomChinaNameColumn = 5;
            //14 加工日期
            //int PcbOutDateColumn = 14;
            //15 路径
            //int PcbPathColumn = 15;

            ProStatus.Text = "正在处理,请稍后...";
            /*处理两个工作表分别为：料单样板、器件库*/
            //Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            Microsoft.Office.Interop.Excel.Application workbook = new Microsoft.Office.Interop.Excel.Application();//实例化Excel对象
            object missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            //打开指定的Excel文件
            Microsoft.Office.Interop.Excel.Workbook OutWorkBook = workbook.Application.Workbooks.Open(@filename, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            OutWorkBook.Application.DisplayAlerts = false;
            Excel.Range range;

            int PcbNum = 0;

            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "PCB输出样板")
                {
                    PcbNum = i;
                }
            }
            //PCB输出样板存副本
            Excel.Worksheet PcbOutSheet = workbook.Worksheets[PcbNum];//要操作的表的索引。
            PcbOutSheet.Name = "PCB输出";

            int idnum = 1; int PCBrow = 4;

            //说明只有一行
            if (16 >= ConfigList.Count)
            {
                //设置一下行高
                for (int i = 0; i < 24; i++)
                {
                    range = PcbOutSheet.Rows[5, this.missing];
                    range.Delete(Excel.XlDirection.xlDown);
                }
                range = PcbOutSheet.Rows[4, this.missing];
                range.RowHeight = "100";
            }


            for (int i = 0; i < ConfigList.Count; )
            {
                //序号
                PcbOutSheet.Cells[PCBrow, SerialColumn] = idnum; idnum++;
                //PCB板名
                //PCB版本                                     项目名称      加      BOM文件名   加       版本        加  中文名
                PcbOutSheet.Cells[PCBrow, PcbNameColumn] = ConfigList[i + 1] + ConfigList[i + 3] + ConfigList[i + 6] + "(" + ConfigList[i + 4] + ")";
                //PCB尺寸
                PcbOutSheet.Cells[PCBrow, PcbSizeColumn] = ConfigList[i + 7];
                //板内日期
                PcbOutSheet.Cells[PCBrow, PcbDateColumn] = ConfigList[i + 8];
                //下单数量
                PcbOutSheet.Cells[PCBrow, PcbNumberColumn] = ConfigList[i + 10];
                //板层数
                PcbOutSheet.Cells[PCBrow, PcbLayerColumn] = ConfigList[i + 9];
                //厚度
                PcbOutSheet.Cells[PCBrow, PcbThicknessColumn] = ConfigList[i + 11];
                //软件版本
                //加工工艺
                PcbOutSheet.Cells[PCBrow, SoftRevColumn] = "工艺;" + ConfigList[i + 12] + "  设计软件：" + ConfigList[i + 15];
                PCBrow++;
                i = i + 16;
            }                       
            
            //删除多余的行
            int tempdel = (28 - PCBrow);
            int temprow = PCBrow;
            for (int i = 1; i < tempdel; i++)
            {
                range = PcbOutSheet.Rows[temprow, this.missing];
                range.Delete(Excel.XlDirection.xlDown);
            }           


            //自定义页脚
            PcbOutSheet.PageSetup.LeftFooter = @"编制:" + textBoxcompile.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");
            PcbOutSheet.PageSetup.CenterFooter = @"审核:" + textBoxCheck.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");
            PcbOutSheet.PageSetup.RightFooter = @"批准:" + textBoxRatify.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");

            OutWorkBook.Save();//保存工作表
            OutWorkBook.Close(false, missing, missing);//关闭工作表
        }

        
        //输出所有的表
        public void OutAllBom()
        {

             if (ConfigList.Count < 1)
	        {
                MessageBox.Show("没有要输出的文件，是否没有保存配置表，如果没有，请先填好配置并保存后再输出。");
                return;
	        }

            SaveFileDialog saveexcel = new SaveFileDialog();
            saveexcel.Filter = "Excel文件|*.xlsx";

            if (saveexcel.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (16 >= ConfigList.Count)
            {
                File.Copy(@"C:\BOM\Excel2007样板单表.xlsx", @saveexcel.FileName, true);
            }
            else
            {
                File.Copy(@"C:\BOM\Excel2007样板.xlsx", @saveexcel.FileName, true);
            }            

            ProStatus.Text = "正在处理。请稍后。。。";

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//实例化Excel对象
            object missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            //打开指定的Excel文件
            Microsoft.Office.Interop.Excel.Workbook OutWorkBook = excel.Application.Workbooks.Open(@saveexcel.FileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            OutWorkBook.Application.DisplayAlerts = false;
            Excel.Worksheet SingleBomSheet;
            Excel.Range range;
            //复制一个表
            object Missing = System.Reflection.Missing.Value;                   //获取缺少的object类型值            

            //------------------------单表一个一个的生成-----------------------------------------
            for (int i = 0; i < ConfigList.Count; )
            {
                //----------读取当前单表内容到SingleBomList列表中--------------------------------
                //读取分表内容到SingleBomList中去
                ReadSingleBomToList(ConfigList[i + 3]);
                //----------读取当前单表内容到SingleBomList列表中结束----------------------------
                int sheetnum = 0;
                for (int s = 0; s < DelBom.Length; s++)
                {
                    for (int j = 1; j <= OutWorkBook.Worksheets.Count; j++)
                    {
                        if (OutWorkBook.Worksheets[j].Name == "料单样板")
                        {
                            sheetnum = j;
                        }
                    }
                }

                SingleBomSheet = OutWorkBook.Worksheets[sheetnum];

                if (i + 16 < ConfigList.Count)
                {
                    SingleBomSheet.Copy(Missing, SingleBomSheet);
                    //料单样板
                    SingleBomSheet = OutWorkBook.Worksheets[sheetnum + 1]; //要操作的表的索引。
                }

                //单表的名字
                SingleBomSheet.Name = ConfigList[i + 3];        // ComSheets.Text;              


                ProStatus.Text = "正在生成分表：" + ConfigList[i + 3] + "。请稍后。。。";
                
                //写入到要输出的单表
                int count = SingleBomList.Count / 9 + 3;
                for (int TempRow = 3; TempRow < count; TempRow++)//遍历数据集中表的行数
                {
                    for (int TempColumn = 1; TempColumn < 10; TempColumn++)                                                          //遍历数据集中表的列数
                    {
                        if (TempColumn==2)
                        {
                            SingleBomSheet.Cells[TempRow, TempColumn] = "";
                           // SingleBomSheet.Cells[TempRow, 10] = SingleBomList[((TempRow - 3) * 9) + (TempColumn - 1)]; ; 
                        }
                        else
                        {
                            if (SingleBomList[((TempRow - 3) * 9) + (TempColumn - 1)] == "nc删除")
                            {
                                SingleBomSheet.Cells[TempRow, TempColumn] = "";
                            }
                            else
                            {
                                SingleBomSheet.Cells[TempRow, TempColumn] = SingleBomList[((TempRow - 3) * 9) + (TempColumn - 1)];
                            }

                            if ((TempColumn==9)&&(SingleBomList[((TempRow - 3) * 9) + (TempColumn - 1)] == "替"))
                            {
                                SingleBomSheet.Cells[TempRow, TempColumn] = "";
                            }
                        }

                    }
                }

                //自定义页眉
                SingleBomSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
                                                                                         //输出项目名称+BOM名+版本+中文名
                SingleBomSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18" + ConfigList[i + 1] + ConfigList[i + 3] + ConfigList[i + 6] + "(" + ConfigList[i + 4] + ")" + "元件清单";
                SingleBomSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" + comboBoxBomRev.Text;// textBoxBomRev.Text;
                //自定义页脚
                SingleBomSheet.PageSetup.LeftFooter = @"&""微软雅黑,常规""日期:" + dateTimePicker1.Text;
                SingleBomSheet.PageSetup.CenterFooter = @"&""微软雅黑,常规""第&P页/共&N页";
                SingleBomSheet.PageSetup.RightFooter = "";
                i = i + 16;
            }//所有单表输出结束
            //------------------------单表一个一个的生成结束----------------------------


            if (16 >= ConfigList.Count) 
            {
                OutWorkBook.Save();//保存工作表
                OutWorkBook.Close(false, missing, missing);//关闭工作表
                //输出PCB文件
                PcbOut(@saveexcel.FileName);
                //-------------------------输出记录表内容--------------------------------
                OutRec(@saveexcel.FileName);
                //-------------------------输出记录表内容结束----------------------------
                ProStatus.Text = "处理完成。";
                MessageBox.Show("处理完成。");
                return;
            }


           


            //------------封面开始------------------------------------------------------
            ProStatus.Text = "正在生成“总表封面”。请稍后。。。";
            int AllBom = 0;
 
            for (int j = 1; j <= OutWorkBook.Worksheets.Count; j++)
            {
                if (OutWorkBook.Worksheets[j].Name == "总表封面样板")
                {
                    AllBom = j;
                }
            }
            SingleBomSheet = OutWorkBook.Worksheets[AllBom];//要操作的表的索引。
            SingleBomSheet.Name = "总表封面";

            range = SingleBomSheet.Range[SingleBomSheet.Cells[10, 3], SingleBomSheet.Cells[13, 22]]; //项目名称
            range.ClearContents(); //先把Range内容清除，合并才不会出错
            range.MergeCells = true;
            range.Value2 = textBoxAllTitle.Text + "汇总表";

            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
            range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
            range.Name = "微软雅黑";
            range.Font.FontStyle = "常规"; ;
            range.Font.Size = 36;

            range = SingleBomSheet.Range[SingleBomSheet.Cells[20, 10], SingleBomSheet.Cells[21, 16]]; //项目名称
            range.ClearContents(); //先把Range内容清除，合并才不会出错
            range.MergeCells = true;
            range.Value2 = "文件共     页";

            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
            range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
            range.Name = "微软雅黑";
            range.Font.FontStyle = "常规"; ;
            range.Font.Size = 20;


            //自定义页眉
            SingleBomSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
            //AllBomSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18" + textBoxAllTitle.Text + "汇总表";
            SingleBomSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" + textBoxAllRev.Text;// textBoxBomRev.Text;
            //自定义页脚
            SingleBomSheet.PageSetup.LeftFooter = @"编制:" + textBoxcompile.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");
            SingleBomSheet.PageSetup.CenterFooter = @"审核:" + textBoxCheck.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");
            SingleBomSheet.PageSetup.RightFooter = @"批准:" + textBoxRatify.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");

            //-----------封面结束------------------------------------------------------


            //删除多余的表-----有问题很慢，不知什么原因且不结束------------------------
            //for (int s = 0; s < delbomname.Length; s++)
            //{
            //    for (int j = 1; j <= OutWorkBook.Worksheets.Count; j++)
            //    {
            //        if (OutWorkBook.Worksheets[j].Name == delbomname[s])
            //        {
            //            SingleBomSheet = OutWorkBook.Worksheets[j];
            //            SingleBomSheet.Delete();
            //        }
            //    }
            //}
            //删除多余的表结束--------------------------------------------------------

            OutWorkBook.Save();//保存工作表
            OutWorkBook.Close(false, missing, missing);//关闭工作表
           
            
            //----------------------------输出总表-----------------------------------
            ProStatus.Text = "正在生成“总表”。请稍后。。。";
            CollectOut(@saveexcel.FileName);
            //----------------------------输出总表结束-------------------------------
            
            //输出PCB文件
            //----------------------------PCB输出------------------------------------
            ProStatus.Text = "正在生成“PCB输出”。请稍后。。。";
            PcbOut(@saveexcel.FileName);
            //----------------------------PCB输出结束--------------------------------

            //-------------------------输出记录表内容--------------------------------
            OutRec(@saveexcel.FileName);
            //-------------------------输出记录表内容结束----------------------------

            ProStatus.Text = "完成处理";
            MessageBox.Show("完成导出！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        
        }



        //读取记录表内容到ReadRecList
        public void ReadRec(string filename)
        {
            Excel.Workbook workbookthis = this.Application.Workbooks[1];    //工作簿
            Excel.Range range;
            Excel.Worksheet CSheet;
            string TempStr;

            ReadRecList.Clear();
            
            for (int k = 1; k <= workbookthis.Worksheets.Count; k++)
            {
                if (workbookthis.Worksheets[k].Name == "更改记录(" + filename + ")")
                {
                    CSheet = workbookthis.Worksheets[k];
                    for (int i = 2; i < 2000; i++)
                    {
                        range = CSheet.Range[CSheet.Cells[i, 1], CSheet.Cells[i, 1]];   //第2-4列内容为器件名称，规格型号，封装
                        TempStr = range.Text.ToString();
                        if (TempStr == "")
                            break;
                        for (int j = 1; j < 13; j++)
                        {
                            range = CSheet.Range[CSheet.Cells[i, j], CSheet.Cells[i, j]];   //第2-4列内容为器件名称，规格型号，封装
                            TempStr = range.Text.ToString();
                            ReadRecList.Add(TempStr);
                        }                        
                    }
                }
            }
        }
        
        //输出更改记录表
        public void OutRec(string filename)
        {

            /*处理两个工作表分别为：料单样板、器件库*/
            //Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            Microsoft.Office.Interop.Excel.Application workbook = new Microsoft.Office.Interop.Excel.Application();//实例化Excel对象
            object missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            //打开指定的Excel文件
            Microsoft.Office.Interop.Excel.Workbook OutWorkBook = workbook.Application.Workbooks.Open(@filename, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            OutWorkBook.Application.DisplayAlerts = false;
            Excel.Worksheet CSheet;

            for (int i = 0; i < BomNumCount; i++)
            {
                ProStatus.Text = "正在处理，" + BomFileName[i]  + "请稍后。。。";

                //读记录表所有内容
                ReadRec(BomFileName[i]);
                
                //写内容到记录表
                for (int k2 = 1; k2 <= workbook.Worksheets.Count; k2++)
                {
                    if (workbook.Worksheets[k2].Name == "更改记录样板")
                    {
                        CSheet = workbook.Worksheets[k2];
                        object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值

                        if (i+1 < BomNumCount)
                        {
                            CSheet.Copy(Missing, CSheet);
                            //对新建的PCB输出样板进行操作
                            CSheet = workbook.Worksheets[k2 + 1];//要操作的表的索引。
                        }

                        CSheet.Name = "更改记录(" + BomFileName[i] + ")";
                        
                        for (int s = 2; s < 2000; s++)
                        {
                            if (((s - 2) * 12) >= ReadRecList.Count)
                            {
                                break;
                            }
                            for (int n = 1; n < 13; n++)
                            {
                                CSheet.Cells[s, n] = ReadRecList[((s - 2) * 12) + (n - 1)];
                            }
                        }

                        //自定义页眉
                        CSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
                        CSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18" + ConfigList[(i * 16) + 4] + "更改记录(" + BomFileName[i] + ")";
                        CSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:V10";
                        //ConfigList.Add(tempstr);
                       //ConfigList[i];
                        //自定义页脚
                        CSheet.PageSetup.LeftFooter = @"编制:" + textBoxcompile.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");
                        CSheet.PageSetup.CenterFooter = @"审核:" + textBoxCheck.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");
                        CSheet.PageSetup.RightFooter = @"批准:" + textBoxRatify.Text + "  日期:" + DateTime.Now.ToString("yyyy-MM-dd");
                    }
                }
            }

            OutWorkBook.Save();//保存工作表
            OutWorkBook.Close(false, missing, missing);//关闭工作表
            ProStatus.Text = "处理完成";
       
        
        }

         //输出整个文件按键
        private void button8_Click(object sender, EventArgs e)
        {
            ProStatus.Text = "正在处理：分表，总表的导出，请稍后。。。";
            //只有保存了配置并生成了表才能输出
            button8.Enabled = false;
            //输出所有的表
            OutAllBom();
            ProStatus.Text = "处理完成";
        }
        //-------------------输出处理模块结束-------------------------------------------



        //辅助完成整理1备用
        private void button9_Click(object sender, EventArgs e)
        {
            //Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            //int allbom = 0,temprec=0;
            //for (int i = 1; i <= workbook.Worksheets.Count; i++)
            //{
            //    if (workbook.Worksheets[i].Name == "总表")
            //    {
            //        allbom = i;
            //    }
            //    if (workbook.Worksheets[i].Name == "更改记录样板")
            //    {
            //        temprec = i;
            //    }
            //}
            //Excel.Worksheet AllSheet = workbook.Worksheets[allbom];
            //Excel.Worksheet copyrec = workbook.Worksheets[temprec];
            ////复制一个表
            //object Missing = System.Reflection.Missing.Value;                   //获取缺少的object类型值
            //copyrec.Copy(Missing, copyrec);
            ////料单样板
            //Excel.Worksheet rec = workbook.Worksheets[temprec + 1];//要操作的表的索引。
            //rec.Name = "更改记录" + PcbOldCopyCount; PcbOldCopyCount++;
            //Excel.Range range;
            //int  RecRow =2,update=1;          
            //string TempStr = "";

            //for (int TempRow = 5; TempRow < 10000; TempRow++)
            //{
            //    range = AllSheet.Range[AllSheet.Cells[TempRow, 1], AllSheet.Cells[TempRow, 1]];   //第2-4列内容为器件名称，规格型号，封装
            //    TempStr = range.Text.ToString();
            //    if (TempStr == "")
            //        break;
            //    for (int i = 0; i < OkAllList.Count; )
            //    {
            //        if (OkAllList[i] == TempStr)
            //        {
            //            update = 1;
            //            //记录
            //            rec.Cells[RecRow, 1] = RecRow - 1;
            //            rec.Cells[RecRow, 2] = OkAllList[i + 1]; ;
            //            rec.Cells[RecRow, 3] = " -> ";
            //            range = AllSheet.Range[AllSheet.Cells[TempRow, 2], AllSheet.Cells[TempRow, 2]];
            //            TempStr = range.Text.ToString();
            //            if (TempStr == "")
            //            {
            //                rec.Cells[RecRow, 4] = "删除";
            //                range.Interior.ColorIndex = 3;
            //            }
            //            else
            //            {
            //                if (TempStr == OkAllList[i + 1])
            //                { rec.Cells[RecRow, 4] = "保持不变"; update = update+1; }
            //                else
            //                {
            //                    rec.Cells[RecRow, 4] = TempStr;
            //                    range.Interior.ColorIndex = 3;
            //                }
            //            }

            //            rec.Cells[RecRow, 5] = OkAllList[i + 2]; ;
            //            rec.Cells[RecRow, 6] = " -> ";
            //            range = AllSheet.Range[AllSheet.Cells[TempRow, 3], AllSheet.Cells[TempRow, 3]];
            //            TempStr = range.Text.ToString();
            //            if (TempStr == "")
            //            { rec.Cells[RecRow, 7] = "删除"; range.Interior.ColorIndex = 3; }
            //            else
            //            {
            //                if (TempStr == OkAllList[i + 2])
            //                { rec.Cells[RecRow, 7] = "保持不变"; update = update + 1; }
            //                else
            //                { rec.Cells[RecRow, 7] = TempStr; range.Interior.ColorIndex = 3; }
            //            }

            //            rec.Cells[RecRow, 8] = OkAllList[i + 3];
            //            rec.Cells[RecRow, 9] = " -> ";
            //            range = AllSheet.Range[AllSheet.Cells[TempRow, 4], AllSheet.Cells[TempRow, 4]];
            //            TempStr = range.Text.ToString();
            //            if (TempStr == "")
            //            { rec.Cells[RecRow, 10] = "删除"; range.Interior.ColorIndex = 3; }
            //            else
            //            {
            //                if (TempStr == OkAllList[i + 3])
            //                { rec.Cells[RecRow, 10] = "保持不变"; update = update + 1; }
            //                else
            //                {
            //                    rec.Cells[RecRow, 10] = TempStr;
            //                    range.Interior.ColorIndex = 3;
            //                }
            //            }
            //            if (update == 4)
            //            { update = 1; }
            //            else
            //            {RecRow++;}
            //        }
            //        i = i + 4;
            //    }
            //}  
            ////整理一次后自动清除
            ////本来是考虑到一次整理后清除，但有时候发现一次整理后还会有错误的，这个时候就有用处了
            //OkAllList.Clear();
        }
        //测试按建
        private void button10_Click(object sender, EventArgs e)
        {

            //Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            //int allbom = 0, temprec = 0;
            //for (int i = 1; i <= workbook.Worksheets.Count; i++)
            //{
            //    //if (workbook.Worksheets[i].Name == "测试")
            //    //{
            //    //    allbom = i;
            //    //}
            //    if (workbook.Worksheets[i].Name == "更改记录样板")
            //    {
            //        temprec = i;
            //    }
            //}
            //Excel.Worksheet AllSheet = workbook.Worksheets[allbom];
            //Excel.Worksheet copyrec = workbook.Worksheets[temprec];
            ////复制一个表
            //object Missing = System.Reflection.Missing.Value;                   //获取缺少的object类型值
            //copyrec.Copy(Missing, copyrec);
            ////料单样板
            //Excel.Worksheet rec = workbook.Worksheets[temprec + 1];//要操作的表的索引。
            //rec.Name = "更改记录" + PcbOldCopyCount; PcbOldCopyCount++;
            //Excel.Range range;
            
            //OkAllList.Clear();

            //OkAllList.Add("1"); OkAllList.Add("何政1"); OkAllList.Add("测试1"); OkAllList.Add("完成1");
            //OkAllList.Add("2"); OkAllList.Add("何政2"); OkAllList.Add("测试2"); OkAllList.Add("完成2");
            //OkAllList.Add("3"); OkAllList.Add("何政3"); OkAllList.Add("测试3"); OkAllList.Add("完成3");
            //OkAllList.Add("4"); OkAllList.Add("何政4"); OkAllList.Add("测试4"); OkAllList.Add("完成4");
            //OkAllList.Add("5"); OkAllList.Add("何政5"); OkAllList.Add("测试5"); OkAllList.Add("完成5");
            //OkAllList.Add("6"); OkAllList.Add("何政6"); OkAllList.Add("测试6"); OkAllList.Add("完成6");
            //OkAllList.Add("7"); OkAllList.Add("何政7"); OkAllList.Add("测试7"); OkAllList.Add("完成7");

            //int RecRow = 2;

            //string TempStr = "";
            //for (int TempRow = 1; TempRow < 100000; TempRow++)
            //{
            //    range = AllSheet.Range[AllSheet.Cells[TempRow, 1], AllSheet.Cells[TempRow, 1]];   //第2-4列内容为器件名称，规格型号，封装
            //    TempStr = range.Text.ToString();
            //    if (TempStr == "")
            //        break;
            //    for (int i = 0; i < OkAllList.Count; )
            //    {
            //        if (OkAllList[i] == TempStr)
            //        {
            //            //记录
            //            rec.Cells[RecRow, 1] = RecRow - 1;
            //            rec.Cells[RecRow, 2] = OkAllList[i + 1]; ;
            //            rec.Cells[RecRow, 3] = " -> ";
            //            range = AllSheet.Range[AllSheet.Cells[TempRow, 2], AllSheet.Cells[TempRow, 2]];
            //            TempStr = range.Text.ToString();
            //            if (TempStr == "")
            //            {
            //                rec.Cells[RecRow, 4] = "删除";
            //                range.Interior.ColorIndex = 3;
            //            }
            //            else
            //            {
            //                if (TempStr == OkAllList[i + 1])
            //                { rec.Cells[RecRow, 4] = "保持不变"; }
            //                else
            //                {
            //                    rec.Cells[RecRow, 4] = TempStr;
            //                    range.Interior.ColorIndex = 3;
            //                }
            //            }

            //            rec.Cells[RecRow, 5] = OkAllList[i + 2]; ;
            //            rec.Cells[RecRow, 6] = " -> ";
            //            range = AllSheet.Range[AllSheet.Cells[TempRow, 3], AllSheet.Cells[TempRow, 3]];
            //            TempStr = range.Text.ToString();
            //            if (TempStr == "")
            //            { rec.Cells[RecRow, 7] = "删除"; range.Interior.ColorIndex = 3; }
            //            else
            //            {
            //                if (TempStr == OkAllList[i + 2])
            //                { rec.Cells[RecRow, 7] = "保持不变"; }
            //                else
            //                { rec.Cells[RecRow, 7] = TempStr; range.Interior.ColorIndex = 3; }
            //            }

            //            rec.Cells[RecRow, 8] = OkAllList[i + 3];
            //            rec.Cells[RecRow, 9] = " -> ";
            //            range = AllSheet.Range[AllSheet.Cells[TempRow, 4], AllSheet.Cells[TempRow, 4]];
            //            TempStr = range.Text.ToString();
            //            if (TempStr == "")
            //            { rec.Cells[RecRow, 10] = "删除"; range.Interior.ColorIndex = 3; }
            //            else
            //            {
            //                if (TempStr == OkAllList[i + 3])
            //                { rec.Cells[RecRow, 10] = "保持不变"; }
            //                else
            //                {
            //                    rec.Cells[RecRow, 10] = TempStr;
            //                    range.Interior.ColorIndex = 3;
            //                }
            //            }
            //            RecRow++;
            //        }
            //        i = i + 4;
            //    }
            //}
            ////range=rec.Range[rec.Cells[, E], rec.Cells[E, E]]

            ////隐藏某一列，有时要用到，很方便
            //range = rec.Columns[5, this.missing];  //.Rows[5, this.missing];
            //range.EntireColumn.Hidden = true;
            //OkAllList.Clear();
        }
        public void SingleBomReplace()
        {
            List<string> TempSbomList = new List<string>();
            List<string> TempSbomListReplace = new List<string>(); 

            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            string TempStr = "";
            Excel.Worksheet SingleSheet = workbook.Worksheets[1];
            Excel.Range range;

            for (int SingleCount = 0; SingleCount < BomNumCount; SingleCount++) //SingleCount 为表名计数器    BomNumCount为一共多少个表
			{
                for (int i = 1; i <= workbook.Worksheets.Count; i++)             //在总工作表中找
                {
                    if (workbook.Worksheets[i].Name == BomFileName[SingleCount])//找到与BomFileName[SingleCount] 的表名的表，并操作
                    {
                        SingleSheet = workbook.Worksheets[i];
                        // Excel.Range range;

                        //选读取单表内容到TempSbomList中方便查找
                        for (int SinCount = 3; SinCount < 30000; SinCount++)
                        {
                            range = SingleSheet.Range[SingleSheet.Cells[SinCount, 1], SingleSheet.Cells[SinCount, 1]];
                            TempStr = range.Text.ToString();
                            if (TempStr != "")
                            {   //序号
                                TempSbomList.Add(TempStr);
                                //名称
                                range = SingleSheet.Range[SingleSheet.Cells[SinCount, 3], SingleSheet.Cells[SinCount, 3]];
                                TempStr = range.Text.ToString();
                                TempSbomList.Add(TempStr);
                                //规格型号
                                range = SingleSheet.Range[SingleSheet.Cells[SinCount, 4], SingleSheet.Cells[SinCount, 4]];
                                TempStr = range.Text.ToString();
                                TempSbomList.Add(TempStr);
                                //封装
                                range = SingleSheet.Range[SingleSheet.Cells[SinCount, 5], SingleSheet.Cells[SinCount, 5]];
                                TempStr = range.Text.ToString();
                                TempSbomList.Add(TempStr);
                            }
                            else
                            {
                                break;
                            }
                        }




                        //比较并替换，并记录替换内容
                        int Id=1;
                        for (int allcount = 0; allcount < OkSingleAllList.Count;)  //总表内容
                        {
                            for (int SinCount = 0; SinCount < TempSbomList.Count; )  //分表内容
                            {
                                if ((OkSingleAllList[allcount] == TempSbomList[SinCount + 1]))   // 名称是否相等
                                {
                                    if ((OkSingleAllList[allcount + 2] == TempSbomList[SinCount + 2])) // 规格是否相等
                                    {
                                        if ((OkSingleAllList[allcount + 4] == TempSbomList[SinCount + 3])) // 封装是否相等
                                        {
                                            //如果发现完全相同就可以全部替换成替换表的内容
                                            if ((OkSingleAllList[allcount + 1] == "删除") && (OkSingleAllList[allcount + 1] == "删除") && (OkSingleAllList[allcount + 1] == "删除"))
                                            {
                                                TempSbomList[SinCount + 0] = "删";                                                
                                            }
                                            else
                                            {
                                                TempSbomList[SinCount + 0] = "替";
                                            }
                                            //存的为单表内空
                                            TempSbomList[SinCount + 1] = OkSingleAllList[allcount + 1];
                                            TempSbomList[SinCount + 2] = OkSingleAllList[allcount + 3];
                                            TempSbomList[SinCount + 3] = OkSingleAllList[allcount + 5];

                                            //存的为单表记录表内容
                                            TempSbomListReplace.Add(Id.ToString()); Id++;          //1   0  序号
                                            TempSbomListReplace.Add(OkSingleAllList[allcount]);          //0   1  原
                                            TempSbomListReplace.Add(" ->");
                                            TempSbomListReplace.Add(OkSingleAllList[allcount + 1]);
                                            TempSbomListReplace.Add(OkSingleAllList[allcount + 2]);
                                            TempSbomListReplace.Add(" ->");
                                            TempSbomListReplace.Add(OkSingleAllList[allcount + 3]);
                                            TempSbomListReplace.Add(OkSingleAllList[allcount + 4]);
                                            TempSbomListReplace.Add(" ->");
                                            TempSbomListReplace.Add(OkSingleAllList[allcount + 5]);
                                            TempSbomListReplace.Add(OkSingleAllList[allcount + 6]); //时间
                                            TempSbomListReplace.Add(OkSingleAllList[allcount + 7] + "分表行号：" + SinCount); //备注
                                        }
                                    }                                    
                                }
                                SinCount = SinCount + 4;
                            }
                            allcount = allcount + 8;
                        }

                        string tempst1;
                        //重新写入单表的表格
                        for (int SinCount = 3; SinCount < 30000; SinCount++)
                        {
                            range = SingleSheet.Range[SingleSheet.Cells[SinCount, 1], SingleSheet.Cells[SinCount, 1]];
                            TempStr = range.Text.ToString();
                            if (TempStr =="")
                            {
                                break;
                            }
                            else
                            {
                                tempst1 = TempSbomList[(SinCount - 3) * 4 + 0];
                                //序号
                                if ((tempst1=="删")||(tempst1=="替"))
                                {
                                    SingleSheet.Cells[SinCount, 9] = tempst1;// TempSbomList[(SinCount - 3) * 4 + 0];  
                                }
                                
                                //名称
                                if (TempSbomList[(SinCount - 3) * 4 + 1] != "保持不变")
                                {
                                    SingleSheet.Cells[SinCount, 3] = TempSbomList[(SinCount - 3) * 4 + 1];  
                                }
                                if (TempSbomList[(SinCount - 3) * 4 + 2] != "保持不变")
                                {
                                    //规格型号
                                    SingleSheet.Cells[SinCount, 4] = TempSbomList[(SinCount - 3) * 4 + 2];                                    
                                }
                                if (TempSbomList[(SinCount - 3) * 4 + 3] != "保持不变")
                                {
                                    //封装
                                    SingleSheet.Cells[SinCount, 5] = TempSbomList[(SinCount - 3) * 4 + 3];
                                }                                
                            }
                        }



                        //建立分表记录表

                        //删除多余同名的分表记录表
                        for (int k = 1; k <= workbook.Worksheets.Count; k++)             //在总工作表中找
                        {

                            if (workbook.Worksheets[k].Name == "更改记录(" + BomFileName[SingleCount] + ")")//workbook.Worksheets[i].Name
                            {
                                Excel.Worksheet CSheet = workbook.Worksheets[k];
                                CSheet.Name =workbook.Worksheets[k] + "副本" + PcbOldCopyCount; PcbOldCopyCount++; ;  //SingleSheet.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
                            }
                        }


                        //写内容到记录表
                        for (int k2 = 1; k2 <= workbook.Worksheets.Count; k2++)
                        {                            
                            if (workbook.Worksheets[k2].Name == "更改记录样板")
                            {
                                SingleSheet = workbook.Worksheets[k2];
                                object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
                                SingleSheet.Copy(Missing, SingleSheet);
                                //对新建的PCB输出样板进行操作
                                SingleSheet = workbook.Worksheets[k2 + 1];//要操作的表的索引。
                                SingleSheet.Name = "更改记录(" + BomFileName[SingleCount] + ")";
                                int recrows = 0;
                                for (int s = 2; s < 2000; s++)
                                {
                                    if (((s - 2) * 12) >= TempSbomListReplace.Count)
                                    {
                                        recrows = s;
                                        break;
                                    }
                                    for (int n = 1; n < 13; n++)
                                    {
                                        SingleSheet.Cells[s, n] = TempSbomListReplace[((s - 2) * 12) + (n - 1)];
                                    }
                                }

                                //进行排一下序AllSheet.Cells[i, 10 + BomNumCount]
                                range = SingleSheet.Range[SingleSheet.Cells[2, 1], SingleSheet.Cells[recrows, 12]];
                                //按3列升序排序
                                range.Sort(
                                 range.Columns[2, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
                                 range.Columns[7, missing], missing, Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
                                 range.Columns[10, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
                                 Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing, missing,
                                 Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortColumns,
                                 Microsoft.Office.Interop.Excel.XlSortMethod.xlPinYin,
                                 Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
                                 Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
                                 Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal);

                                int ID00 = 1;
                                for (int ij = 2; ij < recrows + 1; ij++)
                                {
                                    SingleSheet.Cells[ij, 1] = ID00; ID00++;
                                }

                            }
                        }



                        SingleSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
                        SingleSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18" + ConfigList[SingleCount * 16 + 4] + "更改记录(" + BomFileName[SingleCount] + ")";
                        SingleSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" + textBoxAllRev.Text;
                        //自定义页脚
                        SingleSheet.PageSetup.LeftFooter = @"&""微软雅黑,常规""日期:" + dateTimePicker3.Text;
                        SingleSheet.PageSetup.CenterFooter = @"&""微软雅黑,常规""第&P页/共&N页";
                        SingleSheet.PageSetup.RightFooter = "";

                        TempSbomList.Clear();
                        TempSbomListReplace.Clear();
                    }
                }  
			 
			}


        }
        
        //替换单表
        private void button12_Click(object sender, EventArgs e)
        {
            SingleBomReplace();
            button20.Enabled=true;
            MessageBox.Show("替换单表完成！");    
        }

        public void fuzhu()
        {

            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int AllBom = 0, test = 0;
            string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "总表")
                {
                    AllBom = i;
                }
                if (workbook.Worksheets[i].Name == "更改记录样板")
                {
                    test = i;
                }
                if (workbook.Worksheets[i].Name == "更改记录(总表)")
                {
                    Excel.Worksheet DELcopy = workbook.Worksheets[i];
                    DELcopy.Name = DELcopy.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
                }
            }

            Excel.Worksheet AllSheet = workbook.Worksheets[AllBom];
            Excel.Worksheet copyrec = workbook.Worksheets[test];
            //复制一个表
            object Missing = System.Reflection.Missing.Value;                   //获取缺少的object类型值
            copyrec.Copy(Missing, copyrec);
            //料单样板
            Excel.Worksheet testSheet = workbook.Worksheets[test + 1];//要操作的表的索引。
            testSheet.Name = "更改记录(总表)";
            Excel.Range range;
            string TempStr = "";
            int rowstemp = 0;
            //清总表所有的色彩为无色
            for (int js = 5; js < 20000; js++)
            {
                range = AllSheet.Range[AllSheet.Cells[js, 1], AllSheet.Cells[js, 1]];
                TempStr = range.Text.ToString();
                if (TempStr == "")
                {
                    rowstemp = js - 1;
                    break;
                }
                else
                {
                    range = AllSheet.Range[AllSheet.Cells[js, 1], AllSheet.Cells[js, 1]];
                    range.Interior.ColorIndex = 0;
                    range = AllSheet.Range[AllSheet.Cells[js, 2], AllSheet.Cells[js, 2]];
                    range.Interior.ColorIndex = 0;
                    range = AllSheet.Range[AllSheet.Cells[js, 3], AllSheet.Cells[js, 3]];
                    range.Interior.ColorIndex = 0;
                    range = AllSheet.Range[AllSheet.Cells[js, 4], AllSheet.Cells[js, 4]];
                    range.Interior.ColorIndex = 0;
                }
            }

            //进行排一下序AllSheet.Cells[i, 10 + BomNumCount]
            range = AllSheet.Range[AllSheet.Cells[5, 1], AllSheet.Cells[rowstemp, 4]]; //4 有点问题 改为-> 10 + BomNumCount + 1              
            range.Sort(
             range.Columns[2, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[4, missing], missing, Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[3, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing, missing,
             Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortColumns,
             Microsoft.Office.Interop.Excel.XlSortMethod.xlPinYin,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal);

            //自定义排序
            menfun();
            sortfunv11();

            int S2 = 0, recrows = 2, S4 = 0; //rows
            for (int i = 5; i < 20000; i++)
            {
                AllSheet.Cells[i, 5] = "";
                range = AllSheet.Range[AllSheet.Cells[i, 1], AllSheet.Cells[i, 1]];
                TempStr = range.Text.ToString();
                if (TempStr == "")
                    break;
                int s = 0;
                for (int k = 0; k < OkAllList.Count; )
                {
                    if (TempStr == OkAllList[k])
                    {
                        s = k;
                        break;
                    }
                    k = k + 4;

                }

                //生成更换记录表
                if (s != 0)
                {
                    S2 = 0;
                    for (int j = 1; j < 5; j++)
                    {
                        range = AllSheet.Range[AllSheet.Cells[i, j], AllSheet.Cells[i, j]];
                        TempStr = range.Text.ToString();
                        switch (j)
                        {
                            case 1:

                                testSheet.Cells[recrows, 1] = recrows - 1;
                                break;
                            case 2:
                                testSheet.Cells[recrows, 2] = OkAllList[s + 1];
                                testSheet.Cells[recrows, 3] = " ->";
                                if (OkAllList[s + 1] == TempStr)
                                {
                                    testSheet.Cells[recrows, 4] = "保持不变";
                                }
                                else
                                { testSheet.Cells[recrows, 4] = TempStr; S2 = 2; range.Interior.ColorIndex = 3; AllSheet.Cells[i, 5] = "替:" + OkAllList[s + 0]; }
                                if (TempStr == "")
                                { testSheet.Cells[recrows, 4] = "删除"; S2 = 2; S4 = 2; range.Interior.ColorIndex = 3; AllSheet.Cells[i, 2] = "删除";  AllSheet.Cells[i, 5] = "删:" + OkAllList[s + 0]; }
                                break;
                            case 3:
                                testSheet.Cells[recrows, 5] = OkAllList[s + 2];
                                testSheet.Cells[recrows, 6] = " ->";
                                if (OkAllList[s + 2] == TempStr)
                                {
                                    testSheet.Cells[recrows, 7] = "保持不变";
                                }
                                else
                                { testSheet.Cells[recrows, 7] = TempStr; S2 = 2; range.Interior.ColorIndex = 3; AllSheet.Cells[i, 5] = "替:" + OkAllList[s + 0]; }
                                if (TempStr == "")
                                { testSheet.Cells[recrows, 7] = "删除"; S2 = 2; S4 = 2; range.Interior.ColorIndex = 3; AllSheet.Cells[i, 3] = "删除";  AllSheet.Cells[i, 5] = "删:" + OkAllList[s + 0]; }
                                break;
                            case 4:
                                testSheet.Cells[recrows, 8] = OkAllList[s + 3];
                                testSheet.Cells[recrows, 9] = " ->";
                                if (OkAllList[s + 3] == TempStr)
                                {
                                    testSheet.Cells[recrows, 10] = "保持不变";
                                }
                                else
                                { testSheet.Cells[recrows, 10] = TempStr; S2 = 2; range.Interior.ColorIndex = 3; AllSheet.Cells[i, 5] = "替:" + OkAllList[s + 0]; }
                                if (TempStr == "")
                                { testSheet.Cells[recrows, 10] = "删除"; S2 = 2; S4 = 2; range.Interior.ColorIndex = 3; AllSheet.Cells[i, 4] = "删除"; AllSheet.Cells[i, 5] = "删:" + OkAllList[s + 0]; }
                                break;
                            default:
                                break;
                        }
                    }

                    //日期
                    testSheet.Cells[recrows, 11] = DateTime.Now.ToString("yyyy-MM-dd"); //dateTimePicker1.Text;// DateTime.Now.ToString("yyyy-MM-dd"); "  总表行号： " + i;


                    range = AllSheet.Range[AllSheet.Cells[i,5 ], AllSheet.Cells[i,5 ]];//10 + BomNumCount 10 + BomNumCount
                    TempStr = range.Text.ToString();
                    if (TempStr == "")
                    {
                        testSheet.Cells[recrows, 12] = "  总表行号： " + i;
                    }
                    else
                    {
                        testSheet.Cells[recrows, 12] = TempStr + "  总表行号： " + i;
                        //AllSheet.Cells[4, 5] = "辅助标记";
                        //AllSheet.Cells[i, 5] = "替:" + TempStr;
                    }

                    if (S2 == 2)
                    {
                        recrows++;
                    }

                    S2 = 0; S4 = 0;
                }//  记录生成结束            
            } //FOR记录生成结束


            //最后一行判断 是否要删除
            string ST1, ST2, ST3;
            range = testSheet.Range[testSheet.Cells[recrows, 4], testSheet.Cells[recrows, 4]];
            ST1 = range.Text.ToString();

            range = testSheet.Range[testSheet.Cells[recrows, 7], testSheet.Cells[recrows, 7]];
            ST2 = range.Text.ToString();

            range = testSheet.Range[testSheet.Cells[recrows, 10], testSheet.Cells[recrows, 10]];
            ST3 = range.Text.ToString();
            //删除最后一行
            if ((ST1 == "保持不变") && (ST2 == "保持不变") && (ST3 == "保持不变"))
            {
                range = testSheet.Rows[recrows, this.missing];
                range.Delete(Excel.XlDirection.xlDown);
                recrows = recrows - 1;
            }
            //最后一行判断结束

            //进行排一下序AllSheet.Cells[i, 10 + BomNumCount]
            range = testSheet.Range[testSheet.Cells[2, 1], testSheet.Cells[recrows, 12]];
            //按3列升序排序
            range.Sort(
             range.Columns[2, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[7, missing], missing, Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[10, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing, missing,
             Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortColumns,
             Microsoft.Office.Interop.Excel.XlSortMethod.xlPinYin,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal);

            int ID00 = 1;
            for (int i = 2; i < recrows+1; i++)
            {
                testSheet.Cells[i, 1] = ID00; ID00++;                
            }


            testSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
            testSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18总表元件清单更改记录";
            testSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" + textBoxAllRev.Text;
            //自定义页脚
            testSheet.PageSetup.LeftFooter = @"&""微软雅黑,常规""日期:" + dateTimePicker3.Text;
            testSheet.PageSetup.CenterFooter = @"&""微软雅黑,常规""第&P页/共&N页";
            testSheet.PageSetup.RightFooter = "";



            //存储后查单表替换记录
            OkSingleAllList.Clear();
            for (int RecRows = 2; RecRows < 30000; RecRows++)
            {
                range = testSheet.Range[testSheet.Cells[RecRows, 1], testSheet.Cells[RecRows, 1]];
                ST1 = range.Text.ToString();
                if (ST1 == "")
                {
                    break;
                }
                for (int RecCol = 2; RecCol < 13; RecCol++)
                {
                    range = testSheet.Range[testSheet.Cells[RecRows, RecCol], testSheet.Cells[RecRows, RecCol]];
                    ST1 = range.Text.ToString();
                    if (ST1 != " ->")
                    {
                        OkSingleAllList.Add(ST1);
                    }
                }
            }
            ProStatus.Text = "处理完成";

            //打开单表替换功能
            button12.Enabled = true;

            //替换单表时有用
            //SingleBomReplace();

            MessageBox.Show("处理完成");
        
        }

        //辅助整理总表
        private void button11_Click(object sender, EventArgs e)
        {
            //range = ReplaceSheet.Range[ReplaceSheet.Cells[TempRow, 1], ReplaceSheet.Cells[TempRow, 1]];
            //range.Interior.ColorIndex = 3; 

            fuzhu();         

        }



        private void ComSheets_MouseDown(object sender, MouseEventArgs e)
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            ComSheets.Items.Clear();
            ComSheets.Text = "请选择";
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
               ComSheets.Items.Add(workbook.Worksheets[i].Name);
            }

        }


        //导出报表为文本
        private void ExprotReplace_Click(object sender, EventArgs e)
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            Excel.Worksheet ReplaceSheet = workbook.Worksheets[1];

            Excel.Range range ;

           string Tempstr="",AllStr="";
           StreamWriter SWriter = new StreamWriter(@"E:\"+ ComSheets.Text + ".txt", false, Encoding.Default);//实例化写入流对象

            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == ComSheets.Text) 
                {
                    ReplaceSheet = workbook.Worksheets[i];
                    for (int row = 2; row < 2000; row++)
                    {
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 2], ReplaceSheet.Cells[row, 2]];
                        Tempstr = range.Text.ToString();
                        if (Tempstr=="")
                        {
                            break;
                        }

                        //器件名称
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 2], ReplaceSheet.Cells[row, 2]];
                        Tempstr = range.Text.ToString();
                        AllStr = AllStr + Tempstr;
                        AllStr += Environment.NewLine;//字符串换行
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 4], ReplaceSheet.Cells[row, 4]];
                        Tempstr = range.Text.ToString();
                        AllStr = AllStr + Tempstr;
                        AllStr += Environment.NewLine;//字符串换行

                        //规格型号
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 5], ReplaceSheet.Cells[row, 5]];
                        Tempstr = range.Text.ToString();
                        AllStr = AllStr + Tempstr;
                        AllStr += Environment.NewLine;//字符串换行
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 7], ReplaceSheet.Cells[row, 7]];
                        Tempstr = range.Text.ToString();
                        AllStr = AllStr + Tempstr;
                        AllStr += Environment.NewLine;//字符串换行

                        //封装
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 8], ReplaceSheet.Cells[row, 8]];
                        Tempstr = range.Text.ToString();
                        AllStr = AllStr + Tempstr;
                        AllStr += Environment.NewLine;//字符串换行
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 10], ReplaceSheet.Cells[row, 10]];
                        Tempstr = range.Text.ToString();
                        AllStr = AllStr + Tempstr;
                        AllStr += Environment.NewLine;//字符串换行
                   
                    }       //多行内容完成
                    SWriter.Write(AllStr);//先文本文件中写入内容
                    SWriter.Close();//关闭写入流对象
                    SWriter.Dispose();//释放写入流所占用的资源
                    //MessageBox.Show("已经将" + cbox_SheetName.Text + "工作表中的数据成功写入到了文本文件中", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);    
                } 
            }
      }

        
        //读取字符  处理字符  保存字符
        private void button13_Click(object sender, EventArgs e)
        {
            //读取
            string Replace_Line;                                                                                //记录读取行的内容及遍历到的内容 监时字符串
            List<string> Replace_List = new List<string>();                                                     //存储读取的所有内容
            StreamReader ReplaceReader = new StreamReader(@"E:\"+ ComSheets.Text + ".txt", Encoding.Default);  //实例化流读取对象
            while ((Replace_Line = ReplaceReader.ReadLine()) != null)                                           //循环读取文本文件中的每一行
            {
                Replace_List.Add(Replace_Line);                                                                 //将读取到的行内容添加到泛型集合中
            }
            ReplaceReader.Close();
            ReplaceReader.Dispose();

            //处理
            Replace_List.RemoveAt(2);
            Replace_List.RemoveRange(2, 5);
            
            //重组写入
            string AllStr = "";
            for (int i = 0; i < Replace_List.Count; i++)
            {
                AllStr = AllStr + Replace_List[i];
                AllStr += Environment.NewLine;//字符串换行
            }

            //写入
            StreamWriter SWriter = new StreamWriter(@"E:\" + ComSheets.Text + ".txt", false, Encoding.Default);//实例化写入流对象
            SWriter.Write(AllStr);//先文本文件中写入内容
            SWriter.Close();//关闭写入流对象
            SWriter.Dispose();//释放写入流所占用的资源

        }

        //把读取的内容写入到记事本上
        public void WriterLibFile()
        {
            //重组写入
            string AllStr = "";
            for (int i = 0; i < Lib_List.Count; i++)
            {
                AllStr = AllStr + Lib_List[i].Replace("\n","");
                AllStr += Environment.NewLine;//字符串换行
            }
            //写入
            StreamWriter SWriter = new StreamWriter(@"E:\AllLib.txt", false, Encoding.Default);//实例化写入流对象
            SWriter.Write(AllStr);//先文本文件中写入内容
            SWriter.Close();//关闭写入流对象
            SWriter.Dispose();//释放写入流所占用的资源
        }

        //增加一条记录到器件库中
        public int AddLib(string partname, string partmodel, string partfoot)
        {
            string TempStr = "";
            if (LibFlag)
            {
                //读取退出
                StreamReader ReplaceReader = new StreamReader(AllLibPath, Encoding.Default);  //实例化流读取对象
                while ((TempStr = ReplaceReader.ReadLine()) != null)                                           //循环读取文本文件中的每一行
                {
                    Lib_List.Add(TempStr);                                                                 //将读取到的行内容添加到泛型集合中
                }
                ReplaceReader.Close();
                ReplaceReader.Dispose();
                LibFlag = false; //读取完成标志已读
            }//读取结束      

            //获取最后的行号并加1为当前行号
            int num = Convert.ToInt16(Lib_List[Lib_List.Count - 4]) + 1, exists = 0;

            //查找重复
            for (int libi = 0; libi < Lib_List.Count; )
            {
                if ((Lib_List[libi + 1] == partname) && (Lib_List[libi + 2] == partmodel) && (Lib_List[libi + 3] == partfoot))
                {
                    exists = 10;
                    break;
                }
                libi = libi + 4;
            }

            if (exists == 10)
            {
                exists = 0;//如果重复就不用加入库内
                return 0;
            }
            else
            {
                exists = 0;
                Lib_List.Add(num.ToString()); num++;
                Lib_List.Add(partname.Replace("\n", ""));
                Lib_List.Add(partmodel.Replace("\n", ""));
                Lib_List.Add(partfoot.Replace("\n", ""));
                return 1; //说明要加入到器件库中
            }    
        }

        //新增可替换的内容
        private void button15_Click(object sender, EventArgs e)
        {
            //读取
            string Replace_Line;                                                                                //记录读取行的内容及遍历到的内容 监时字符串
            List<string> Replace_List = new List<string>();                                                     //存储读取的所有内容
            //存储等待添加的内容
            List<string> ReplaceAddList = new List<string>();


            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            Excel.Worksheet ReplaceSheet = workbook.Worksheets[1];

            Excel.Range range;
            string Tempstr = "", AllStr = "";
            
            string SName = "", RName = "", SPart = "", RPart = "", Sfoot = "", Rfoot = "",Date="",Note="";
            int addflag = 0;
            int AddPartCount = 0;
            ReplaceAddList.Clear();
            
            //读取退出
            StreamReader ReplaceReader = new StreamReader(ReplacePath, Encoding.Default);  //实例化流读取对象
            while ((Replace_Line = ReplaceReader.ReadLine()) != null)                                           //循环读取文本文件中的每一行
            {
                Replace_List.Add(Replace_Line);                                                                 //将读取到的行内容添加到泛型集合中
            }
            ReplaceReader.Close();
            ReplaceReader.Dispose();

            int id = (Replace_List.Count / 8) + 1; //序号

            //比较去除重复，加入新内容
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == ComSheets.Text)
                {
                    ReplaceSheet = workbook.Worksheets[i];
                    for (int row = 2; row < 2000; row++)
                    {
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 2], ReplaceSheet.Cells[row, 2]];
                        Tempstr = range.Text.ToString();
                        if (Tempstr == "")
                        {
                            break;
                        }
                        //序号
                        //range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 2], ReplaceSheet.Cells[row, 2]];
                        // string ID = range.Text.ToString();
                        //器件名称
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 2], ReplaceSheet.Cells[row, 2]];
                        SName = range.Text.ToString();
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 4], ReplaceSheet.Cells[row, 4]];
                        RName = range.Text.ToString();
                        //规格型号
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 5], ReplaceSheet.Cells[row, 5]];
                        SPart = range.Text.ToString();
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 7], ReplaceSheet.Cells[row, 7]];
                        RPart = range.Text.ToString();
                        //封装
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 8], ReplaceSheet.Cells[row, 8]];
                        Sfoot = range.Text.ToString();
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 10], ReplaceSheet.Cells[row, 10]];
                        Rfoot = range.Text.ToString();
                        //日期
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 11], ReplaceSheet.Cells[row, 11]];
                        Date = range.Text.ToString();
                        //备注
                        range = ReplaceSheet.Range[ReplaceSheet.Cells[row, 12], ReplaceSheet.Cells[row, 12]];
                        Note = range.Text.ToString();

                        if ((SName != RName) && (RPart=="保持不变") && (Rfoot=="保持不变"))
                        {
                            //这种内容不加到替换表上，而是加到库里面去
                            if (AddLib(RName, SPart, Sfoot) > 0)
                            {
                                AddPartCount++;
                            }                             
                        }
                        else
                        {
                            for (int j = 0; j < Replace_List.Count; )
                            {
                                if ((SName == Replace_List[j]) && (RName == Replace_List[j + 1]) && (SPart == Replace_List[j + 2]) && (RPart == Replace_List[j + 3]) && (Sfoot == Replace_List[j + 4]) && (Sfoot == Replace_List[j + 5]))
                                {
                                    addflag = 1;
                                    break;
                                }
                                j = j + 6;
                            }
                            //等于1说明不用添加
                            if (addflag != 1)
                            {
                                //Lib_List[i].Replace("\n","")
                                ReplaceAddList.Add(id.ToString()); //序号
                                ReplaceAddList.Add(SName.Replace("\n", ""));
                                ReplaceAddList.Add(RName.Replace("\n", ""));
                                ReplaceAddList.Add(SPart.Replace("\n", ""));
                                ReplaceAddList.Add(RPart.Replace("\n", ""));
                                ReplaceAddList.Add(Sfoot.Replace("\n", ""));
                                ReplaceAddList.Add(Rfoot.Replace("\n", ""));
                                ReplaceAddList.Add(Date.Replace("\n", ""));
                                if (Note == "")
                                {
                                    Note = "无";
                                }
                                ReplaceAddList.Add(Note);
                                id++;
                            }
                            addflag = 0;
                        }
                    } //多行内容完成
                }//结束替换表内容的加入
            }//找到表的名称

            if (Replace_List.Count > 0)
            {
                //重组写入          
                for (int i = 0; i < Replace_List.Count; i++)
                {
                    AllStr = AllStr + Replace_List[i];
                    AllStr += Environment.NewLine;//字符串换行
                }

                if (ReplaceAddList.Count > 0)
                {
                    for (int j = 0; j < ReplaceAddList.Count; j++)
                    {
                        AllStr = AllStr + ReplaceAddList[j];
                        AllStr += Environment.NewLine;//字符串换行
                    }
                }

                //写入
                StreamWriter SWriter = new StreamWriter(ReplacePath, false, Encoding.Default);//实例化写入流对象
                SWriter.Write(AllStr);//先文本文件中写入内容
                SWriter.Close();//关闭写入流对象
                SWriter.Dispose();//释放写入流所占用的资源
            }

            //重组写入 器件库
            AllStr = "";
            if (AddPartCount > 0)
            {                
                for (int i = 0; i < Lib_List.Count; i++)
                {
                    AllStr = AllStr + Lib_List[i];
                    AllStr += Environment.NewLine;//字符串换行
                }
                //写入
                StreamWriter SWriterLib = new StreamWriter(AllLibPath, false, Encoding.Default);//实例化写入流对象
                SWriterLib.Write(AllStr);//先文本文件中写入内容
                SWriterLib.Close();//关闭写入流对象
                SWriterLib.Dispose();//释放写入流所占用的资源                
            }

            MessageBox.Show("新增完成。");
        }


        private void button14_Click(object sender, EventArgs e)
        {

            Form1 form2 = new Form1();
            form2.Show();            
            //form2.TopMost = true;
            //form2.MinimumSize(); 
           // MaximumSize(980, 600);
        }

        //器件库转为大写
        private void button16_Click(object sender, EventArgs e)
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int  PartLib = 0;
            string[] tabname = new string[100];   //workbook.Worksheets.Count存工作簿中所有表名 最多100个表
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "器件库")
                {
                    PartLib = i;
                }
            }

            //器件库
            Excel.Worksheet PartLibSheet = workbook.Worksheets[PartLib];    //要操作的表的索引为器件库。
            Excel.Range range;

            //int Lib_Count = 0;                                                                                                          //存储字符的个数
            string TempStr = "";
           // if (LibFlag)
           // {
                //存储读取库中的内容
                //把器件库中所有器件写入Lib_List进行处理
                for (int TempRow = 1; TempRow < 10000; TempRow++)//遍历数据集中表的行数
                {
                    range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, 1], PartLibSheet.Cells[TempRow, 1]];                         //第1列内容为序号
                    TempStr = range.Text.ToString();
                    if (TempStr == (TempRow.ToString()))
                    {
                        for (int TempColumn = 1; TempColumn < 5; TempColumn++)                                                          //遍历数据集中表的列数
                        {
                            TempStr = "";
                            range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, TempColumn], PartLibSheet.Cells[TempRow, TempColumn]];   //第2-4列内容为器件名称，规格型号，封装
                            TempStr = range.Text.ToString();
                            TempStr = TempStr.ToUpper(); //所有的转换为大写的内容
                            //重新写回去
                            PartLibSheet.Cells[TempRow, TempColumn] = TempStr;
                            //Lib_List.Add(TempStr);//将读取到的行内容添加到泛型集合中
                            //Lib_Count++;//使当前读取行数加1
                        }
                    }
                    else
                    {
                        break;
                    }
                }
               // LibFlag = false; //读取完成标志已读
           // }//读取结束           
            MessageBox.Show("已经将\"器件库.xlsx\"工作表中的数据存到了一个字符串上。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        private void button17_Click(object sender, EventArgs e)
        {
            Addlist();
            MessageBox.Show("OK", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void button18_Click(object sender, EventArgs e)
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int AllBom = 0, test = 0;
            string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "总表")
                {
                    AllBom = i;
                }
                if (workbook.Worksheets[i].Name == "更改记录样板")
                {
                    test = i;
                }
                if (workbook.Worksheets[i].Name == "更改记录(总表)")
                {
                    Excel.Worksheet DELcopy = workbook.Worksheets[i];
                    DELcopy.Name = DELcopy.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
                }
            }

            Excel.Worksheet AllSheet = workbook.Worksheets[AllBom];
            Excel.Worksheet copyrec = workbook.Worksheets[test];
            //复制一个表
            object Missing = System.Reflection.Missing.Value;                   //获取缺少的object类型值
            copyrec.Copy(Missing, copyrec);
            //料单样板
            Excel.Worksheet testSheet = workbook.Worksheets[test + 1];//要操作的表的索引。
            testSheet.Name = "更改记录(总表)";
            Excel.Range range;
            string TempStr = "";

            int S2 = 0, S3 = 2, S4 = 0;
            for (int i = 5; i < 20000; i++)
            {
                range = AllSheet.Range[AllSheet.Cells[i, 1], AllSheet.Cells[i, 1]];
                TempStr = range.Text.ToString();
                if (TempStr == "")
                    break;
                int s = 0;
                for (int k = 0; k < OkAllList.Count; )
                {
                    if (TempStr == OkAllList[k])
                    {
                        s = k;
                        break;
                    }
                    k = k + 4;

                }

                if (s != 0)
                {
                    S2 = 0;
                    for (int j = 1; j < 5; j++)
                    {
                        range = AllSheet.Range[AllSheet.Cells[i, j], AllSheet.Cells[i, j]];
                        TempStr = range.Text.ToString();
                        switch (j)
                        {
                            case 1:

                                testSheet.Cells[S3, 1] = S3 - 1;
                                break;
                            case 2:
                                testSheet.Cells[S3, 2] = OkAllList[s + 1];
                                testSheet.Cells[S3, 3] = " ->";
                                if (OkAllList[s + 1] == TempStr)
                                {
                                    testSheet.Cells[S3, 4] = "保持不变";
                                }
                                else
                                { testSheet.Cells[S3, 4] = TempStr; S2 = 2; range.Interior.ColorIndex = 3; }
                                if (TempStr == "")
                                { testSheet.Cells[S3, 4] = "删除"; S2 = 2; S4 = 2; range.Interior.ColorIndex = 3; }
                                break;
                            case 3:
                                testSheet.Cells[S3, 5] = OkAllList[s + 2];
                                testSheet.Cells[S3, 6] = " ->";
                                if (OkAllList[s + 2] == TempStr)
                                {
                                    testSheet.Cells[S3, 7] = "保持不变";
                                }
                                else
                                { testSheet.Cells[S3, 7] = TempStr; S2 = 2; range.Interior.ColorIndex = 3; }
                                if (TempStr == "")
                                { testSheet.Cells[S3, 7] = "删除"; S2 = 2; S4 = 2; range.Interior.ColorIndex = 3; }
                                break;
                            case 4:
                                testSheet.Cells[S3, 8] = OkAllList[s + 3];
                                testSheet.Cells[S3, 9] = " ->";
                                if (OkAllList[s + 3] == TempStr)
                                {
                                    testSheet.Cells[S3, 10] = "保持不变";
                                }
                                else
                                { testSheet.Cells[S3, 10] = TempStr; S2 = 2; range.Interior.ColorIndex = 3; }
                                if (TempStr == "")
                                { testSheet.Cells[S3, 10] = "删除"; S2 = 2; S4 = 2; range.Interior.ColorIndex = 3; }
                                break;
                            default:
                                break;
                        }
                    }

                    if (S2 == 2)
                    {
                        AllSheet.Cells[i, 1] = "替";
                        testSheet.Cells[S3, 11] = Convert.ToDateTime(dateTimePicker3.Text).ToString("yyyy-MM-dd");// dateTimePicker3.Text;
                    }
                    if (S4 == 2)
                    {
                        AllSheet.Cells[i, 1] = "删";
                    }
                    if (S2 == 2)
                    {
                        S3++;
                    }

                    S2 = 0; S4 = 0;
                }
            }

            string ST1, ST2, ST3;
            range = testSheet.Range[testSheet.Cells[S3, 4], testSheet.Cells[S3, 4]];
            ST1 = range.Text.ToString();

            range = testSheet.Range[testSheet.Cells[S3, 7], testSheet.Cells[S3, 7]];
            ST2 = range.Text.ToString();

            range = testSheet.Range[testSheet.Cells[S3, 10], testSheet.Cells[S3, 10]];
            ST3 = range.Text.ToString();
            //删除最后一行
            if ((ST1 == "保持不变") && (ST2 == "保持不变") && (ST3 == "保持不变"))
            {
                range = testSheet.Rows[S3, this.missing];
                range.Delete(Excel.XlDirection.xlDown);
            }

            OkSingleAllList.Clear();

            for (int RecRows = 2; RecRows < 30000; RecRows++)
            {
                range = testSheet.Range[testSheet.Cells[RecRows, 1], testSheet.Cells[RecRows, 1]];
                ST1 = range.Text.ToString();
                if (ST1 == "")
                {
                    break;
                }
                for (int RecCol = 2; RecCol < 13; RecCol++)
                {
                    range = testSheet.Range[testSheet.Cells[RecRows, RecCol], testSheet.Cells[RecRows, RecCol]];
                    ST1 = range.Text.ToString();
                    if (ST1 != " ->")
                    {
                        OkSingleAllList.Add(ST1);
                    }
                }
            }
            ProStatus.Text = "处理完成";
            testSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
            testSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18总表元件清单更改记录";
            testSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" + textBoxAllRev.Text;
            //自定义页脚
            testSheet.PageSetup.LeftFooter = @"&""微软雅黑,常规""日期:" + dateTimePicker3.Text;
            testSheet.PageSetup.CenterFooter = @"&""微软雅黑,常规""第&P页/共&N页";
            testSheet.PageSetup.RightFooter = "";


            //替换单表时有用
           // SingleBomReplace();

            MessageBox.Show("处理完成");
        }
        //
        private void button19_Click(object sender, EventArgs e)
        {
            ProStatus.Text = "正在处理,请稍后...";

            label1.Text = "";
            label2.Text = "";
            label3.Text = "";
            comboBox1.Items.Clear();
            comboBox1.Text = "";
            comboBox2.Items.Clear();
            comboBox2.Text = "";
            comboBox3.Items.Clear();
            comboBox3.Text = "";
            FindList.Clear();
            ProCount = 0;

            if (LibFlag)//等于真没有加载过
                Lib_List.Clear();
            

            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int sheetnum = 0, PartLib = 0;
            string[] tabname = new string[100];   //workbook.Worksheets.Count存工作簿中所有表名 最多100个表
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                tabname[i - 1] = workbook.Worksheets[i].Name;       // + " "存工作簿
                if (workbook.Worksheets[i].Name == "料单样板")
                {
                    sheetnum = i;
                }
                if (workbook.Worksheets[i].Name == "器件库")
                {
                    PartLib = i;
                }
            }

            //ProStatus.BackColor = ;
            //器件库
            Excel.Worksheet PartLibSheet = workbook.Worksheets[PartLib];    //要操作的表的索引为器件库。
            Excel.Range range;

            int Lib_Count = 0;                                                                                                          //存储字符的个数
            string TempStr = "";
            
            List<string> TempLib_List = new List<string>();     //存储读取的所有内容

            StreamReader ReplaceReader = new StreamReader(AllLibPath, Encoding.Default);  //实例化流读取对象
            while ((TempStr = ReplaceReader.ReadLine()) != null)                                           //循环读取文本文件中的每一行
            {
                TempLib_List.Add(TempStr);                                                                 //将读取到的行内容添加到泛型集合中
            }
            ReplaceReader.Close();
            ReplaceReader.Dispose();
            


            //存储读取库中的内容
            //把器件库中所有器件写入Lib_List进行处理
            for (int TempRow = 1; TempRow < 10000; TempRow++)//遍历数据集中表的行数
            {
                range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, 1], PartLibSheet.Cells[TempRow, 1]];                         //第1列内容为序号
                TempStr = range.Text.ToString();
                if (TempStr == (TempRow.ToString()))
                {
                    for (int TempColumn = 1; TempColumn < 5; TempColumn++)                                                          //遍历数据集中表的列数
                    {
                        TempStr = "";
                        range = PartLibSheet.Range[PartLibSheet.Cells[TempRow, TempColumn], PartLibSheet.Cells[TempRow, TempColumn]];   //第2-4列内容为器件名称，规格型号，封装
                        TempStr = range.Text.ToString();
                        TempStr = TempStr.ToUpper(); //所有的转换为大写的内容
                        Lib_List.Add(TempStr);//将读取到的行内容添加到泛型集合中
                        Lib_Count++;//使当前读取行数加1
                    }
                }
                else
                {
                    break;
                }
            }

            for (int i = 4000; i < TempLib_List.Count + 4000; i++)
			{
                //if (TempLib_List[i] != Lib_List[i]) 
                //{
                //    MessageBox.Show(TempLib_List[i] +"不等于"+ i + Lib_List[i]);
                //}

                PartLibSheet.Cells[i, 1] = TempLib_List[i-4000];
                


			}

            for (int i = 4000; i < Lib_List.Count + 4000; i++)
            {    

                
                PartLibSheet.Cells[i, 2] = Lib_List[i - 4000];


            }
            


            MessageBox.Show("ok");

        }


        private void button20_Click(object sender, EventArgs e)
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            Excel.Worksheet AllSheet = workbook.Worksheets[1];
            Excel.Range range;
            int AllBom = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "总表")
                {
                    AllBom = i;
                }
            }

            AllSheet = workbook.Worksheets[AllBom];
            //Excel.Range range;
            int rowstemp = 0;

            for (int i = 5; i < 20000; )
            {
                //清除以前没用的色彩标记
                AllSheet.Cells[i, 5] = "";
                range = AllSheet.Range[AllSheet.Cells[i, 2], AllSheet.Cells[i, 2]];
                range.Interior.ColorIndex = 0;
                range = AllSheet.Range[AllSheet.Cells[i, 3], AllSheet.Cells[i, 3]];
                range.Interior.ColorIndex = 0;
                range = AllSheet.Range[AllSheet.Cells[i, 4], AllSheet.Cells[i, 4]];
                range.Interior.ColorIndex = 0; 
                range = AllSheet.Range[AllSheet.Cells[i, 1], AllSheet.Cells[i, 1]];
                range.Interior.ColorIndex = 0; 

                if (range.Text.ToString() != "")
                {
                    range = AllSheet.Range[AllSheet.Cells[i, 2], AllSheet.Cells[i, 2]];
                    if ((range.Text.ToString() == "删除") || (range.Text.ToString() == ""))
                    {
                        range = AllSheet.Rows[i, this.missing];
                        range.Delete(Excel.XlDirection.xlDown);
                    }
                    else
                    {
                        i++;
                    }
                }
                else
                {
                    rowstemp = i-1;
                    break;
                }
            }

            //进行排一下序AllSheet.Cells[i, 10 + BomNumCount]
            range = AllSheet.Range[AllSheet.Cells[5, 1], AllSheet.Cells[rowstemp, 4]];//10 + BomNumCount + 1
            //按3列升序排序
            range.Sort(
             range.Columns[2, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[4, missing], missing, Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[3, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing, missing,
             Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortColumns,
             Microsoft.Office.Interop.Excel.XlSortMethod.xlPinYin,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal);

            //自定义排序
            menfun();
            sortfunv11();

            //重新生成一个新排列序号
            int ids = 1;
            for (int i = 5; i < 20000;i++ )
            {
                range = AllSheet.Range[AllSheet.Cells[i, 1], AllSheet.Cells[i, 1]];
                if (range.Text.ToString() != "")
                {
                    AllSheet.Cells[i, 1] = Convert.ToString(ids); ids++;
                }
                else
                {
                    break;
                }
            }
            

            int SingleBom = 0;
            string tempstr;
            //表分删除多余的行
            for (int tables = 0; tables < BomNumCount; tables++)
            {
                for (int i = 1; i <= workbook.Worksheets.Count; i++)
                {
                    if (workbook.Worksheets[i].Name == BomFileName[tables])
                    {
                        SingleBom = i;
                    }
                }
                AllSheet = workbook.Worksheets[SingleBom];

                //AllSheet.Cells[1, 11] = "辅助标记";
                for (int s = 3; s < 20000; )
                {
                    range = AllSheet.Range[AllSheet.Cells[s, 1], AllSheet.Cells[s, 1]];
                    tempstr = range.Text.ToString();
                    if (tempstr == "")
                    {
                        rowstemp = s-1;
                        break;
                    }

                    range = AllSheet.Range[AllSheet.Cells[s, 9], AllSheet.Cells[s, 9]];
                    tempstr = range.Text.ToString();
                    
                    if (tempstr == "删")
                    {
                        range = AllSheet.Rows[s, this.missing];
                        range.Delete(Excel.XlDirection.xlDown);
                    }
                    else
                    {
                        if (tempstr == "替")
                        {
                            AllSheet.Cells[s, 9] = "";
                            //AllSheet.Cells[s, 11] = "替";
                        }
                        s++;
                    }

                }

                //进行排一下序
                range = AllSheet.Range[AllSheet.Cells[3, 1], AllSheet.Cells[rowstemp, 9]];
                range.Sort(
                             range.Columns[3, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
                             range.Columns[5, missing], missing, Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
                             range.Columns[4, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
                             Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing, missing,
                             Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortColumns,
                             Microsoft.Office.Interop.Excel.XlSortMethod.xlPinYin,
                             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
                             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
                             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal);

                //自定义排序
                menfun();
                sortfunv12(BomFileName[tables]);

                //重新生成一个新排列序号
                ids = 1;
                for (int k = 3; k < 20000; k++)
                {
                    range = AllSheet.Range[AllSheet.Cells[k, 1], AllSheet.Cells[k, 1]];
                    if (range.Text.ToString() != "")
                    {
                        AllSheet.Cells[k, 1] = Convert.ToString(ids); ids++;
                    }
                    else
                    {
                        break;
                    }
                }                
            }

           // ressort("总表");

            Addlist();

            MessageBox.Show("处理完成。");
        }

        List<string> ConfigList = new List<string>();     //存储配置表内容

        public void ConfigPro(string prosel)
        {
            string tempstr;
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int BomNum = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "多表配置")
                {
                    BomNum = i;
                }
            }
            if (BomNum == 0)
            {
                return; 
            }
 
            Excel.Worksheet BomConfigSheet = workbook.Worksheets[BomNum];//要操作的表的索引。
            Excel.Range range;
            string ts1, ts2, ts3,ts4;
            bool tf = false;
            if (debugmode.Checked != true )
            {
                if (prosel == "单表")
                {

                    range = BomConfigSheet.Range[BomConfigSheet.Cells[2, 2], BomConfigSheet.Cells[2, 2]];
                    ts1 = range.Text.ToString();
                    range = BomConfigSheet.Range[BomConfigSheet.Cells[2, 5], BomConfigSheet.Cells[2, 5]];
                    ts2 = range.Text.ToString();
                    range = BomConfigSheet.Range[BomConfigSheet.Cells[2, 7], BomConfigSheet.Cells[2, 7]];
                    ts3 = range.Text.ToString();
                    ts4 = "";
                    tf = false;
                    if (ts1 == "L1305(样板)")
                    {
                        ts4 = ts4 + "第2行 项目名称请重新输入！\n";
                        tf = true;
                    }
                    if (ts2 == "机车信号主机板(样板)")
                    {
                        ts4 = ts4 + "第2行 中文名请重新输入！\n";
                        tf = true;
                    }
                    if (ts3 == "V10(样板)")
                    {
                        ts4 = ts4 + "第2行 版本请重新输入！\n";
                        tf = true;
                    }
                    if (tf)
                    {
                        MessageBox.Show(ts4 + "请完善配置表。", "配置表错误");
                        return;
                    }

                }
                else
                {
                    for (int j = 2; j < 10000; j++)
                    {
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[j, 1], BomConfigSheet.Cells[j, 1]];
                        tempstr = range.Text.ToString();
                        if (tempstr == "")
                        {
                            break;
                        }

                        ts1 = ""; ts2 = ""; ts3 = ""; ts4 = "";
                        tf = false;

                        range = BomConfigSheet.Range[BomConfigSheet.Cells[j, 2], BomConfigSheet.Cells[j, 2]];
                        ts1 = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[j, 5], BomConfigSheet.Cells[j, 5]];
                        ts2 = range.Text.ToString();
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[j, 7], BomConfigSheet.Cells[j, 7]];
                        ts3 = range.Text.ToString();
                        ts4 = "";
                        tf = false;
                        if (ts1 == "L1305(样板)")
                        {
                            ts4 = ts4 + "第" + (j + 1) + "行 项目名称请重新输入！\n";
                            tf = true;
                        }
                        if (ts2 == "机车信号主机板(样板)")
                        {
                            ts4 = ts4 + "第" + (j + 1) + "行 中文名请重新输入！\n";
                            tf = true;
                        }
                        if (ts3 == "V10(样板)")
                        {
                            ts4 = ts4 + "第" + (j + 1) + "行 版本请重新输入！\n";
                            tf = true;
                        }
                        if (tf)
                        {
                            MessageBox.Show(ts4 + "请完善配置表。", "配置表错误");
                            return;
                        }
                    }

                    ts1 = ""; ts2 = ""; ts3 = ""; ts4 = "";
                    tf = false;
                    if (textBoxAllTitle.Text == "LYF1305机车信号(样板)")
                    {
                        ts4 = ts4 + "总表首页 名称请重新输入。 \n";
                        tf = true;
                    }

                    if (textBoxAllRev.Text == "V10(样板)")
                    {
                        ts4 = ts4 + "总表首页 版本请重新输入。 \n";
                        tf = true;
                    }

                    if (tf)
                    {
                        MessageBox.Show(ts4 + "请完善总表首页信息。", "总表首页错误");
                        return;
                    }

                }
                
            } 


            ConfigList.Clear();

            if (prosel=="单表")
            {
                for (int i = 1; i < 17; i++)
                {
                    range = BomConfigSheet.Range[BomConfigSheet.Cells[2, i], BomConfigSheet.Cells[2, i]];
                    tempstr = range.Text.ToString();
                    ConfigList.Add(tempstr);
                    switch (i)
                    {
                        case 2: //项目名称
                            textBoxProduct.Text = tempstr;
                            break;
                        case 3: //打印日期
                            dateTimePicker1.Text = tempstr;
                            break;
                        case 4://bom表名
                            TextBoxBomName.Text = tempstr;  
                            break;
                        case 5: //中文名
                            textBoxChinaName.Text = tempstr;
                            break;
                        case 6://PCB板名
                            textBoxPCB.Text = tempstr;
                            break;
                        case 7://PCB版本
                            comboBoxBomRev.Text = tempstr;
                            break;
                        case 8://PCB尺寸
                            textBoxSize.Text = tempstr;
                            break;
                        case 9://PCB板内日期
                            PcbDate.Text = tempstr;
                            break;
                        case 10: //板层
                            comboBoxLayer.Text = tempstr;
                            break;
                        case 11://下单数量
                            textBoxPcbNum.Text = tempstr;
                            break;
                        case 12://厚度
                            comboBoxThickness.Text = tempstr;
                            break;
                        case 13://加工工艺
                            TechnologyText.Text = tempstr;
                            break;
                        case 15: //目录及文件名 路径 
                            BomPath.Text = tempstr;
                            break;
                        case 16: //软件版本 
                            comboBoxSoftRev.Text = tempstr;
                            break;
                        default:
                            break;
                    }
                }    
            }

            if (prosel=="多表")
            {
                for (int j = 2; j < 10000; j++)
                {
                    range = BomConfigSheet.Range[BomConfigSheet.Cells[j, 1], BomConfigSheet.Cells[j, 1]];
                    tempstr = range.Text.ToString();
                    if (tempstr == "")
                    {
                        break;
                    }
                    for (int i = 1; i < 17; i++)
                    {
                        range = BomConfigSheet.Range[BomConfigSheet.Cells[j, i], BomConfigSheet.Cells[j, i]];
                        tempstr = range.Text.ToString();
                        ConfigList.Add(tempstr);
                        if (j==2)
                        {
                            switch (i)
                            {
                                case 2: //项目名称
                                    textBoxProduct.Text = tempstr;
                                    break;
                                case 3: //打印日期
                                    dateTimePicker1.Text = tempstr;
                                    break;
                                case 4://bom表名
                                    TextBoxBomName.Text = tempstr;
                                    break;
                                case 5: //中文名
                                    textBoxChinaName.Text = tempstr;
                                    break;
                                case 6://PCB板名
                                    textBoxPCB.Text = tempstr;
                                    break;
                                case 7://PCB版本
                                    comboBoxBomRev.Text = tempstr;
                                    break;
                                case 8://PCB尺寸
                                    textBoxSize.Text = tempstr;
                                    break;
                                case 9://PCB板内日期
                                    PcbDate.Text = tempstr;
                                    break;
                                case 10: //板层
                                    comboBoxLayer.Text = tempstr;
                                    break;
                                case 11://下单数量
                                    textBoxPcbNum.Text = tempstr;
                                    break;
                                case 12://厚度
                                    comboBoxThickness.Text = tempstr;
                                    break;
                                case 13://加工工艺
                                    TechnologyText.Text = tempstr;
                                    break;
                                case 15: //目录及文件名 路径 
                                    BomPath.Text = tempstr;
                                    break;
                                case 16: //软件版本 
                                    comboBoxSoftRev.Text = tempstr;
                                    break;
                                default:
                                    break;
                            }//switch结束
                        }//是否等于2
                    }//列FOR结束
                }//行FOR结束
            }//总表结束
           
        }

        //单表保存配置
        private void button21_Click(object sender, EventArgs e)
        {
            ConfigPro("单表");
            //使能转换BOM
            button1.Enabled = true;
            ProStatus.Text = "处理完成。";
        }

        //多表保存配置
        private void button22_Click(object sender, EventArgs e)
        {
            //保存当前配表
            ConfigPro("多表");             

            bool flag = false;
            if (ConfigList.Count > 5)
            {
                //查找配置表内部重复
                for (int i = 0; i < ConfigList.Count; )
                {
                    for (int k = 0; k < ConfigList.Count; )
                    {
                        if ((i != k) && (ConfigList[i + 4] == ConfigList[k + 4]))
                        {
                            MessageBox.Show("有重复的中文板名，请修改后再保存。", "提示");
                            flag = true;
                            goto out1;
                            // break;                        
                        }

                        k = k + 16;
                    }
                    i = i + 16;
                }

            out1:
                if (flag)
                {
                    MessageBox.Show("配置表保存   不  成功。");
                    ProStatus.Text = "配置表保存   不  成功，请修改后再保存。";
                }
                else
                {
                    //查找重复
                    //DoubleKiller() //返回值等于1就是表有重复
                    DoubleKiller();
                    //多表合并使能
                    button4.Enabled = true;
                    //旧表的多表合并使能
                    // button31.Enabled = true;
                    MessageBox.Show("保存配置表成功。");
                    ProStatus.Text = "处理完成。";
                }            
                
            }
            
        }

        private void button23_Click(object sender, EventArgs e)
        {

        }


        //添加一个记录到配置表
        public void SaveConfigList(int ID)
        {
            //要加一个是否记录已存在判断
            int id = ID;
            string strPath = ConfigPath;


            XElement xe = XElement.Load(strPath);
            IEnumerable<XElement> elements1 = from element in xe.Elements("OrderOut")
                                              select element;
            //生成新的编号
            string str = (Convert.ToInt32(elements1.Max(element => element.Attribute("ID").Value)) + 1).ToString("00000");
            
            XElement people = new XElement(
                   "OrderOut", new XAttribute("ID", str),
                    new XElement("ProName", ConfigList[id + 1]),                       //项目名称
                    new XElement("PrintDate", ConfigList[id + 2]),                     //打印日期
                    new XElement("BomFileName", ConfigList[id + 3]),                   //BOM表名
                    new XElement("BomChinaName", ConfigList[id + 4]),                  //BOM中文名
                    new XElement("PcbName", ConfigList[id + 5]),                       //PCB板名
                    new XElement("PcbRev", ConfigList[id + 6]),                        //PCB版本
                    new XElement("PcbSize", ConfigList[id + 7]),                       //PCB尺寸
                    new XElement("PcbDate", ConfigList[id + 8]),                       //PCB板内日期
                    new XElement("PcbLayer", ConfigList[id + 9]),                      //PCB层数
                    new XElement("PcbNumber", ConfigList[id + 10]),                    //PCB下单数量
                    new XElement("PcbThickness", ConfigList[id + 11]),                 //PCB厚度
                    new XElement("PcbCraft", ConfigList[id + 12]),                     //PCB工艺
                    new XElement("PcbOutDate", ConfigList[id + 13]),                   //PCB加工日期                    
                                                                                       //PCB路径 以后要加后缀名
                    new XElement("PcbPath", @"C:\BOM\BOM\PCB\" + ConfigList[id + 1] + ConfigList[id + 3] + ConfigList[id + 6] + ConfigList[id + 8] + ".pcb" ),                      
                    new XElement("PcbSoft", ConfigList[id + 15]),                      //PCB设计软件
                    new XElement("ReserveOne", @"C:\BOM\BOM\" + ConfigList[id + 1] + ConfigList[id + 3] + ConfigList[id + 6] + ConfigList[id + 8] + ".xml"),                   //PCB设计软件
                    new XElement("ReserveTwo", @"C:\BOM\BOM\" + ConfigList[id + 1] + ConfigList[id + 3] + ConfigList[id + 6] + ConfigList[id + 8] + "更改记录.xml")                   //PCB设计软件
                );
            xe.Add(people);
            xe.Save(strPath);         
        }


        string PublicSinglebomPath="";
        
        //创建一个新的料单文件
        public void CreateBomXml(int ID)
        {
            int id = ID;// * 16;
            //文件名等于  项目名称 + 板名 + 版本 + 日期
             PublicSinglebomPath = @"C:\BOM\BOM\" + ConfigList[id + 1] + ConfigList[id + 3] + ConfigList[id + 6] + ConfigList[id + 8] + ".xml";
             id = 0;
            XDocument doc = new XDocument(
                                new XDeclaration("1.0", "utf-8", "yes"),
                                new XElement("BomSXML",                               //单表 数据库
                                new XElement("BomXML",                                //一个单表
                                new XAttribute("ID", "00001"),                         //ID自生成
                                new XElement("SerialNum", SingleBomList[id+0]),       //序号
                                new XElement("ComNum", "nc删除"),                     //统一编号
                                new XElement("PartName", SingleBomList[id+2]),        //器件名称
                                new XElement("PartModel", SingleBomList[id+3]),       //器件型号
                                new XElement("PartFoot",SingleBomList[id+4]),         //器件封装
                                new XElement("PartNum", SingleBomList[id+5]),         //器件数量
                                new XElement("PartNumS",SingleBomList[id+6]),         //器件编号
                                new XElement("OutNumS", "nc删除"),                    //加工数量
                                new XElement("Notes", SingleBomList[id+8])            //备注
                                )
                                )
                              );
            doc.Save(PublicSinglebomPath);
        }


        //添加一个记录
        public void AddBomRowS(int ID)
        {
            int id = ID;// *16;

            XElement xe = XElement.Load(PublicSinglebomPath);
            IEnumerable<XElement> elements1 = from element in xe.Elements("BomXML")
                                              select element;
            //生成新的编号
            string str = (Convert.ToInt32(elements1.Max(element => element.Attribute("ID").Value)) + 1).ToString("00000");

            XElement people = new XElement(
                   "BomXML", new XAttribute("ID", str),
                //new XAttribute("ID", "00001"),                             //ID自生成
                    new XElement("SerialNum", SingleBomList[id + 0]),       //序号
                    new XElement("ComNum", "nc删除"),                       //统一编号
                    new XElement("PartName", SingleBomList[id + 2]),        //器件名称
                    new XElement("PartModel", SingleBomList[id + 3]),       //器件型号
                    new XElement("PartFoot", SingleBomList[id + 4]),        //器件封装
                    new XElement("PartNum", SingleBomList[id + 5]),         //器件数量
                    new XElement("PartNumS", SingleBomList[id + 6]),        //器件编号
                    new XElement("OutNumS", "nc删除"),                      //加工数量
                    new XElement("Notes", SingleBomList[id + 8])            //备注
                );
            xe.Add(people);
            xe.Save(PublicSinglebomPath); 
        }
      
        //查重复测试
        private void button29_Click(object sender, EventArgs e)
        {
                   
       }

        //生成更改记录文件
        public void CreateBomRecXml(int i) 
        {
            int id=i;

            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("ChangeRecordS",                                 //定单输出 数据库
                new XElement("ChangeRecord",                                  //定单输出 一个定单
                new XAttribute("ID", "00001"),                                 //ID                                   
                new XElement("Content", "创建文件，存入料单：当前存入版本日期为："+ ConfigList[id + 1] + ConfigList[id + 3] + ConfigList[id + 6] + ConfigList[id + 8] ),                             //更改内容
                new XElement("Description", "创建文件，生成首个记录。"),                   //更改备注说明
                new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))     //日期
                )
                )
            ); 
            doc.Save(@"C:\BOM\BOM\" + ConfigList[id + 1] + ConfigList[id + 3] + ConfigList[id + 6] + ConfigList[id + 8] + "更改记录.xml");
        }

        //查分表是否有重复的
        public int DoubleKiller()
        {
            //要加一个是否记录已存在判断
            //int id = ID;
            string strPath = ConfigPath;
            int chongfuFlag = 0;
            string chongfu = "多表配置在配置管理器中查找到已存在的记录序号分别为：";

            for (int i = 0; i < ConfigList.Count; )//读配置表总行数
            {
                XElement xes = XElement.Load(strPath);//加载xml文件
                //查询指定名称的元素
                var elements = from element in xes.Elements("OrderOut")
                               where (element.Element("ProName").Value == ConfigList[i + 1]) && (element.Element("BomFileName").Value == ConfigList[i + 3]) && (element.Element("PcbRev").Value == ConfigList[i + 6]) && (element.Element("PcbDate").Value == ConfigList[i + 8])
                               select new
                               {
                                   项目名称 = element.Element("ProName").Value,
                                   打印日期 = element.Element("PrintDate").Value,
                                   BOM表名 = element.Element("BomFileName").Value,
                                   BOM中文名 = element.Element("BomChinaName").Value,
                                   PCB板名 = element.Element("PcbName").Value,
                                   PCB版本 = element.Element("PcbRev").Value,
                                   PCB尺寸 = element.Element("PcbSize").Value,
                                   PCB板内日期 = element.Element("PcbDate").Value,
                                   PCB层数 = element.Element("PcbLayer").Value,
                                   PCB下单数量 = element.Element("PcbNumber").Value,
                                   PCB厚度 = element.Element("PcbThickness").Value,
                                   PCB工艺 = element.Element("PcbCraft").Value,
                                   PCB加工日期 = element.Element("PcbOutDate").Value,
                                   PCB路径 = element.Element("PcbPath").Value,
                                   软件版本 = element.Element("PcbSoft").Value,
                                   BOM路径 = element.Element("ReserveOne").Value,
                                   备用2 = element.Element("ReserveTwo").Value,
                                   ID = element.Attribute("ID").Value,
                               };

                int a = elements.Count();

                if (a > 0)
                {
                    // MessageBox.Show("是重复的");
                    chongfuFlag = 1;
                    chongfu = chongfu + Convert.ToString(i / 16 + 1) + ",";
                }
                else
                {
                    a = 0;
                }

                i = i + 16;
            }
            if (chongfuFlag == 1)
            {
                MessageBox.Show(chongfu + "请检查后重新保存。\n重复原因：项目名称+BOM表名+PCB版本+PCB日期");
                return 1;
            }
            else
            {
                return 0;
            }
        }

        //保存配置 及料单 到数据库k
        private void button24_Click(object sender, EventArgs e)
        {
            //查分表是否有重复的
            if (DoubleKiller() != 1) //等于1就是表有重复
	        {
                for (int i = 0; i < ConfigList.Count; )//读配置表总行数
                {
                    //添加一个配置的行记录
                    SaveConfigList(i);
                    //读取分表内容到SingleBomList中去
                    ReadSingleBomToList(ConfigList[i + 3]);
                    //创建一个文件，加第一条内容添加 SingleBomList
                    CreateBomXml(i);
                    //创建一个更改记录文件
                    CreateBomRecXml(i);
                    //添加所有记录
                    for (int j = 9; j < SingleBomList.Count; )
                    {
                        AddBomRowS(j);
                        j = j + 9;
                    }
                    i = i + 16;
                }

                MessageBox.Show("保存料单成功.","提示");
	        }          
        }


        public void proreplace(string TextBoxBomname)
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int AllBom = 0, test = 0;
            //string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == TextBoxBomname)//要处理的单表
                {
                    AllBom = i;
                }
                if (workbook.Worksheets[i].Name == "更改记录样板")
                {
                    test = i;
                }
                if (workbook.Worksheets[i].Name == "更改记录(" + TextBoxBomname + ")")
                {
                    Excel.Worksheet DELcopy = workbook.Worksheets[i];
                    DELcopy.Name = DELcopy.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
                }
            }

            Excel.Worksheet AllSheet = workbook.Worksheets[AllBom];
            Excel.Worksheet copyrec = workbook.Worksheets[test];
            //复制一个表
            object Missing = System.Reflection.Missing.Value;                   //获取缺少的object类型值
            copyrec.Copy(Missing, copyrec);
            //料单样板
            Excel.Worksheet testSheet = workbook.Worksheets[test + 1];//要操作的表的索引。
            testSheet.Name = "更改记录(" + TextBoxBomname + ")";
            Excel.Range range;
            string TempStr = "";
            int rowstemp = 1;

            for (int i = 3; i < 20000; i++)
            {
                range = AllSheet.Range[AllSheet.Cells[i, 1], AllSheet.Cells[i, 1]];
                TempStr = range.Text.ToString();
                if (TempStr == "")
                {
                    rowstemp = i - 2;
                    break;
                }
            }
            //进行排一下序AllSheet.Cells[i, 10 + BomNumCount]
            range = AllSheet.Range[AllSheet.Cells[3, 1], AllSheet.Cells[rowstemp, 9]]; //  4 有点问题 改为-> 10 + BomNumCount + 1              
            range.Sort(
             range.Columns[2, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[4, missing], missing, Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[3, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing, missing,
             Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortColumns,
             Microsoft.Office.Interop.Excel.XlSortMethod.xlPinYin,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal);

            //自定义排序
            menfun();
            sortfunv12(TextBoxBomname);

            int S2 = 0, recrows = 2, S4 = 0; //rows
            for (int i = 3; i < 20000; i++)
            {
                range = AllSheet.Range[AllSheet.Cells[i, 3], AllSheet.Cells[i, 3]];
                range.Interior.ColorIndex = 0; 
                range = AllSheet.Range[AllSheet.Cells[i, 4], AllSheet.Cells[i, 4]];
                range.Interior.ColorIndex = 0; 
                range = AllSheet.Range[AllSheet.Cells[i, 5], AllSheet.Cells[i, 5]];
                range.Interior.ColorIndex = 0; 
                range = AllSheet.Range[AllSheet.Cells[i, 1], AllSheet.Cells[i, 1]];
                range.Interior.ColorIndex = 0; 
                TempStr = range.Text.ToString();
                if (TempStr == "")
                    break;
                int s = 0;
                for (int k = 0; k < OkAllList.Count; )
                {
                    if (TempStr == OkAllList[k])
                    {
                        s = k;
                        break;
                    }
                    k = k + 4;
                }

                AllSheet.Cells[i, 9] = "";

                //生成更换记录表
                if (s != 0)
                {
                    S2 = 0;
                    for (int j = 1; j < 6; j++)
                    {
                        range = AllSheet.Range[AllSheet.Cells[i, j], AllSheet.Cells[i, j]];
                        TempStr = range.Text.ToString();
                        switch (j)
                        {
                            case 1:

                                testSheet.Cells[recrows, 1] = recrows - 1;
                                break;
                            case 3:
                                testSheet.Cells[recrows, 2] = OkAllList[s + 1];
                                testSheet.Cells[recrows, 3] = " ->";
                                if (OkAllList[s + 1] == TempStr)
                                {
                                    testSheet.Cells[recrows, 4] = "保持不变";
                                }
                                else
                                { testSheet.Cells[recrows, 4] = TempStr; S2 = 2; range.Interior.ColorIndex = 3; AllSheet.Cells[i, 9] = "替："+OkAllList[s]; }
                                if (TempStr == "")
                                { testSheet.Cells[recrows, 4] = "删除"; S2 = 2; S4 = 2; AllSheet.Cells[i, j] = "删除"; AllSheet.Cells[i, 9] = "删：" + OkAllList[s]; range.Interior.ColorIndex = 3; }
                                break;
                            case 4:
                                testSheet.Cells[recrows, 5] = OkAllList[s + 2];
                                testSheet.Cells[recrows, 6] = " ->";
                                if (OkAllList[s + 2] == TempStr)
                                {
                                    testSheet.Cells[recrows, 7] = "保持不变";
                                }
                                else
                                { testSheet.Cells[recrows, 7] = TempStr; S2 = 2; range.Interior.ColorIndex = 3; AllSheet.Cells[i, 9] = "替："+OkAllList[s];}
                                if (TempStr == "")
                                { testSheet.Cells[recrows, 7] = "删除"; S2 = 2; S4 = 2; AllSheet.Cells[i, j] = "删除"; AllSheet.Cells[i, 9] = "删：" + OkAllList[s];range.Interior.ColorIndex = 3; }
                                break;
                            case 5:
                                testSheet.Cells[recrows, 8] = OkAllList[s + 3];
                                testSheet.Cells[recrows, 9] = " ->";
                                if (OkAllList[s + 3] == TempStr)
                                {
                                    testSheet.Cells[recrows, 10] = "保持不变";
                                }
                                else
                                { testSheet.Cells[recrows, 10] = TempStr; S2 = 2; range.Interior.ColorIndex = 3; AllSheet.Cells[i, 9] = "替："+OkAllList[s];}
                                if (TempStr == "")
                                { testSheet.Cells[recrows, 10] = "删除"; S2 = 2; S4 = 2; AllSheet.Cells[i, j] = "删除"; AllSheet.Cells[i, 9] = "删：" + OkAllList[s]; range.Interior.ColorIndex = 3; }
                                break;
                            default:
                                break;
                        }
                    }

                    //日期
                    testSheet.Cells[recrows, 11] = DateTime.Now.ToString("yyyy-MM-dd"); //dateTimePicker1.Text;// DateTime.Now.ToString("yyyy-MM-dd"); "  总表行号： " + i;

                    range = AllSheet.Range[AllSheet.Cells[i, 9], AllSheet.Cells[i, 9]];
                    TempStr = range.Text.ToString();

                    if (TempStr == "")
                    {
                        testSheet.Cells[recrows, 12] = "  分表行号： " + i;
                    }
                    else
                    {
                        testSheet.Cells[recrows, 12] = TempStr + "  分表行号： " + i;
                    }

                    if (S2 == 2)
                    {
                        recrows++;
                    }

                    S2 = 0; S4 = 0;
                }//  记录生成结束            
            } //FOR记录生成结束


            //最后一行判断 是否要删除
            string ST1, ST2, ST3;
            range = testSheet.Range[testSheet.Cells[recrows, 4], testSheet.Cells[recrows, 4]];
            ST1 = range.Text.ToString();

            range = testSheet.Range[testSheet.Cells[recrows, 7], testSheet.Cells[recrows, 7]];
            ST2 = range.Text.ToString();

            range = testSheet.Range[testSheet.Cells[recrows, 10], testSheet.Cells[recrows, 10]];
            ST3 = range.Text.ToString();
            //删除最后一行
            if ((ST1 == "保持不变") && (ST2 == "保持不变") && (ST3 == "保持不变"))
            {
                range = testSheet.Rows[recrows, this.missing];
                range.Delete(Excel.XlDirection.xlDown);
            }
            //最后一行判断结束


            testSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
            testSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18" + TextBoxBomname + "元件清单更改记录";//ConfigList[4]
            testSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" + textBoxAllRev.Text;
            //自定义页脚
            testSheet.PageSetup.LeftFooter = @"&""微软雅黑,常规""日期:" + dateTimePicker3.Text;
            testSheet.PageSetup.CenterFooter = @"&""微软雅黑,常规""第&P页/共&N页";
            testSheet.PageSetup.RightFooter = "";



            //存储后查单表替换记录
            OkSingleAllList.Clear();
            for (int RecRows = 2; RecRows < 30000; RecRows++)
            {
                range = testSheet.Range[testSheet.Cells[RecRows, 1], testSheet.Cells[RecRows, 1]];
                ST1 = range.Text.ToString();
                if (ST1 == "")
                {
                    break;
                }
                for (int RecCol = 2; RecCol < 13; RecCol++)
                {
                    range = testSheet.Range[testSheet.Cells[RecRows, RecCol], testSheet.Cells[RecRows, RecCol]];
                    ST1 = range.Text.ToString();
                    if (ST1 != " ->")
                    {
                        OkSingleAllList.Add(ST1);
                    }
                }
            }
            ProStatus.Text = "处理完成";
            //使能确认按建
            button26.Enabled = true;
        
        }

        //-----------------------辅助整理单表模块----------------------------------
        //辅助整理单表完成
        private void button25_Click(object sender, EventArgs e)
        {
            proreplace(TextBoxBomName.Text);
            MessageBox.Show("处理完成");
        }



        public void delsingle(string TextBoxBomname)
        {

            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            Excel.Worksheet AllSheet = workbook.Worksheets[1];
            Excel.Range range;

            int SingleBom = 0;
            string tempstr;


            //表分删除多余的行
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == TextBoxBomname)
                {
                    SingleBom = i;
                }
            }

            //删除没用的行
            AllSheet = workbook.Worksheets[SingleBom];
            int rowstemp=0;
            for (int s = 3; s < 20000; )
            {
                range = AllSheet.Range[AllSheet.Cells[s, 1], AllSheet.Cells[s, 1]];
                tempstr = range.Text.ToString();
                if (tempstr == "")
                {
                    break;
                }

                range = AllSheet.Range[AllSheet.Cells[s, 3], AllSheet.Cells[s, 3]];
                tempstr = range.Text.ToString();

                if ((tempstr == "删除"))// || (tempstr == "")
                {
                    range = AllSheet.Rows[s, this.missing];
                    range.Delete(Excel.XlDirection.xlDown);
                }
                else
                {
                    s++; rowstemp = s-1;
                }
            }

            ////分表进行排一下序
            range = AllSheet.Range[AllSheet.Cells[3, 1], AllSheet.Cells[rowstemp, 9]];
            range.Sort(
                         range.Columns[3, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
                         range.Columns[5, missing], missing, Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
                         range.Columns[4, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
                         Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing, missing,
                         Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortColumns,
                         Microsoft.Office.Interop.Excel.XlSortMethod.xlPinYin,
                         Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
                         Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
                         Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal);

            //自定义排序
            menfun();
            sortfunv12(TextBoxBomname);

            //重新生成一个新排列序号
            int ids = 1;
            for (int k = 3; k < 20000; k++)
            {
                range = AllSheet.Range[AllSheet.Cells[k, 1], AllSheet.Cells[k, 1]];
                if (range.Text.ToString() != "")
                {
                    AllSheet.Cells[k, 1] = Convert.ToString(ids); ids++;
                    range.Interior.ColorIndex = 0;
                    range = AllSheet.Range[AllSheet.Cells[k, 3], AllSheet.Cells[k, 3]]; range.Interior.ColorIndex = 0;
                    range = AllSheet.Range[AllSheet.Cells[k, 4], AllSheet.Cells[k, 4]]; range.Interior.ColorIndex = 0;
                    range = AllSheet.Range[AllSheet.Cells[k, 5], AllSheet.Cells[k, 5]]; range.Interior.ColorIndex = 0;
                }
                else
                {
                    break;
                }
            }    
        }

        //单表辅助确认按键
        private void button26_Click(object sender, EventArgs e)
        {

            delsingle(TextBoxBomName.Text);
            MessageBox.Show("处理完成。");
        }




        //新增器件库
        private void button27_Click(object sender, EventArgs e)
        {

            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int  AddPartLib = 0;

            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "新增器件库")
                {
                    AddPartLib = i;
                }
            }

            //器件库
            Excel.Worksheet AddPartLibSheet = workbook.Worksheets[AddPartLib];    //要操作的表的索引为器件库。
            Excel.Range range;          

            string TempStr = "";
            if (LibFlag)
            {
                //读取退出
                StreamReader ReplaceReader = new StreamReader(AllLibPath, Encoding.Default);  //实例化流读取对象
                while ((TempStr = ReplaceReader.ReadLine()) != null)                                           //循环读取文本文件中的每一行
                {
                    Lib_List.Add(TempStr);                                                                 //将读取到的行内容添加到泛型集合中
                }
                ReplaceReader.Close();
                ReplaceReader.Dispose();
                LibFlag = false; //读取完成标志已读
            }//读取结束      

            //获取最后的行号并加1为当前行号
            int num = Convert.ToInt16(Lib_List[Lib_List.Count - 4]) + 1, exists=0;       

            string id , partname, partmodel, partfoot;

            for (int i = 2; i < 20000; i++)
            {
                range = AddPartLibSheet.Range[AddPartLibSheet.Cells[i, 1], AddPartLibSheet.Cells[i, 1]];
                TempStr = range.Text.ToString();
                if (TempStr=="")
                {
                    break;                   
                }

                id = TempStr;
                range = AddPartLibSheet.Range[AddPartLibSheet.Cells[i, 2], AddPartLibSheet.Cells[i, 2]];
                TempStr = range.Text.ToString();
                partname = TempStr;
                range = AddPartLibSheet.Range[AddPartLibSheet.Cells[i, 3], AddPartLibSheet.Cells[i, 3]];
                TempStr = range.Text.ToString();
                partmodel = TempStr;
                range = AddPartLibSheet.Range[AddPartLibSheet.Cells[i, 4], AddPartLibSheet.Cells[i, 4]];
                TempStr = range.Text.ToString();
                partfoot = TempStr;

                //查找重复
                for (int libi = 0; libi < Lib_List.Count;)
                {
                    if ((Lib_List[libi + 1] == partname) && (Lib_List[libi + 2] == partmodel) && (Lib_List[libi + 3] == partfoot))
                    {
                        exists = 10;
                        break;
                    }
                    libi = libi + 4;
                }

                if (exists == 10)
                {
                    exists = 0;//如果重复就不用加入库内
                }
                else
                {
                    exists = 0;
                    Lib_List.Add(num.ToString()); num++;
                    Lib_List.Add(partname.Replace("\n",""));
                    Lib_List.Add(partmodel.Replace("\n", ""));
                    Lib_List.Add(partfoot.Replace("\n", ""));                
                }      
          }


            //重组写入
            string AllStr = "";
            for (int i = 0; i < Lib_List.Count; i++)
            {
                AllStr = AllStr + Lib_List[i];
                AllStr += Environment.NewLine;//字符串换行
            }

            //写入
            StreamWriter SWriter = new StreamWriter(AllLibPath, false, Encoding.Default);//实例化写入流对象
            SWriter.Write(AllStr);//先文本文件中写入内容
            SWriter.Close();//关闭写入流对象
            SWriter.Dispose();//释放写入流所占用的资源

            MessageBox.Show("处理完成。");
        }


        //查找重复，但名称不一样的料单
        private void button28_Click(object sender, EventArgs e)
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int AddPartLib = 0;

            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "重复器件")
                {
                    AddPartLib = i;
                }
            }

            //器件库
            Excel.Worksheet AddPartLibSheet = workbook.Worksheets[AddPartLib];    //要操作的表的索引为器件库。
            Excel.Range range;

            string TempStr = "";
            if (LibFlag)
            {
                //读取退出
                StreamReader ReplaceReader = new StreamReader(AllLibPath, Encoding.Default);  //实例化流读取对象
                while ((TempStr = ReplaceReader.ReadLine()) != null)                                           //循环读取文本文件中的每一行
                {
                    Lib_List.Add(TempStr);                                                                 //将读取到的行内容添加到泛型集合中
                }
                ReplaceReader.Close();
                ReplaceReader.Dispose();
                LibFlag = false; //读取完成标志已读
            }//读取结束  

            string id, partname, partmodel, partfoot;
            int[] ids = new int[2000];
            int count = 0,flag=0;

            for (int libis = 0; libis < Lib_List.Count;)
            {
                id = Lib_List[libis + 0];
                partname = Lib_List[libis + 1];
                partmodel = Lib_List[libis + 2];
                partfoot = Lib_List[libis + 3];
                //查找重复
                for (int libi = 0; libi < Lib_List.Count; )
                {
                    if ((Lib_List[libi + 0] != id) && (Lib_List[libi + 2] == partmodel) && (Lib_List[libi + 3] == partfoot))
                    {
                        if (flag==0)
	                    {
                            ids[count] = libis; count++;
                            flag = 1;
	                    }
                        ids[count] = libi; count++;                      
                    }                    
                    libi = libi + 4;
                }
                flag = 0;
                libis = libis + 4;
            }

            if (count > 0)
            {
                for (int row = 1; row < count + 1; row++)
                {
                    AddPartLibSheet.Cells[row, 1] = Lib_List[ids[row - 1] + 0];
                    AddPartLibSheet.Cells[row, 2] = Lib_List[ids[row - 1] + 1];
                    AddPartLibSheet.Cells[row, 3] = Lib_List[ids[row - 1] + 2];
                    AddPartLibSheet.Cells[row, 4] = Lib_List[ids[row - 1] + 3];
                }
            }

            MessageBox.Show("完成。");
        }


        public void writeExcel(int j)
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int BomNum = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "料单样板")
                {
                    BomNum = i;
                }
                if (workbook.Worksheets[i].Name == Convert.ToString(Gstrname[j]))
                {
                    workbook.Worksheets[i].Name = Convert.ToString(Gstrname[j]) + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
                   // CopyBomSheet.Name = CopyBomSheet.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
                }
            }
            //更改上一版本为副本
            Excel.Worksheet SingleSheets = workbook.Worksheets[BomNum];//要操作的表的索引。
            object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            SingleSheets.Copy(Missing, SingleSheets);
            SingleSheets = workbook.Worksheets[BomNum+1];
            SingleSheets.Name =Convert.ToString(Gstrname[j]);

            int iis = tint[j]/ 9 + 3;
            int col1=0;
            for (int trows = 3; trows < iis; trows++)
            {                
                for (int tcol = 1; tcol < 10; tcol++)
                {
                    if (Gstrsingled[j, col1] == "nc删除")
                    {
                        //SingleSheets.Cells[trows, tcol] = "";
                    }
                    else
                    {
                        SingleSheets.Cells[trows, tcol] = Gstrsingled[j, col1];
                    }
                    col1++;                
                } 
            }//读取单表所有行结束 
        }

        

        //文件名
        string[] Gstrname = new string[100];
        //每张表数据个数
        int[] tint = new int[30];
        //记录表的张数
        int Gcount = 0;
        //记录所有单表的内容
        string[,] Gstrsingled = new string[100,9000];

        //打开一个Excel文件
        public bool OpenExcel()
        {

            Gcount = 0;

            string TempPath = "";
            OpenFileDialog openExcel = new OpenFileDialog();        //实例化打开对话框对象
            openExcel.Filter = "Excel文件|*.xlsx|Excel文件|*.xls";  //设置打开文件筛选器
            openExcel.Multiselect = false;                           //设置打开对话框中不能多选

            ProStatus.Text = "正在处理,请稍后...";
            if (openExcel.ShowDialog() != DialogResult.OK)
            {
                return false;
            }

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//实例化Excel对象
            object missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            //打开指定的Excel文件
            Microsoft.Office.Interop.Excel.Workbook OutWorkBook = excel.Application.Workbooks.Open(openExcel.FileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            OutWorkBook.Application.DisplayAlerts = false;
            Excel.Worksheet SingleBomSheet;
            Excel.Range range;
            int col1=0;
            //复制一个表
            object Missing = System.Reflection.Missing.Value;                   //获取缺少的object类型值            
            string tempstr="";
            if (OutWorkBook.Worksheets.Count==1)
            {
                button8.Enabled = true;
                //如果发现是单张表就强制为自动排序和替换
                checkBox1.Checked = true;
                
            }
            for (int i = 1; i <= OutWorkBook.Worksheets.Count; i++)//
            {
                SingleBomSheet = OutWorkBook.Worksheets[i];                
                //判断是否为分表
                range = SingleBomSheet.Range[SingleBomSheet.Cells[1, 3], SingleBomSheet.Cells[1, 3]];                
                tempstr = range.Text.ToString();
                if (tempstr=="器件名称")//说明是个单表
                {
                    Gstrname[Gcount] = SingleBomSheet.Name;
                    //表文件名存入
                    BomFileName[Gcount] = SingleBomSheet.Name;

                    ProStatus.Text = "正在处理：" + SingleBomSheet.Name + "的导入，请稍后。。";
                    for (int trows = 3; trows < 2000; trows++)
                    {
                        range = SingleBomSheet.Range[SingleBomSheet.Cells[trows, 1], SingleBomSheet.Cells[trows, 1]];
                        tempstr = range.Text.ToString();
                        if (tempstr != "")
                        {
                            for (int tcol = 1; tcol < 10; tcol++)
                            {
                                range = SingleBomSheet.Range[SingleBomSheet.Cells[trows, tcol], SingleBomSheet.Cells[trows, tcol]];
                                tempstr = range.Text.ToString();
                                if (tempstr != "")
                                {
                                    tempstr = tempstr.Replace("\n", "");
                                    tempstr = tempstr.ToUpper();
                                    Gstrsingled[Gcount, col1] = tempstr;                               
                                }
                                else
                                {
                                    Gstrsingled[Gcount, col1] = "nc删除";
                                }
                                col1++;
                            }                            
                        }
                        else
                        {
                            //结束读取
                            break;
                        }
                        //写入内容到当前单表中
                       // writeExcel();
                    }//读取单表所有行结束 
                    tint[Gcount] = col1;
                    col1 = 0;
                    Gcount++;                  
                }//读取一个单表
            }//读取所有表结束
            OutWorkBook.Save();//保存工作表
            OutWorkBook.Close(false, missing, missing);//关闭工作表
            
            BomNumCount = Gcount;

            //写入内容到当前单表中
            for (int j = 0; j < Gcount; j++)
            {
                writeExcel(j);
                if (checkBox1.Checked)
                {   //辅助替换处理程序
                    AuxiliaryPro(Convert.ToString(Gstrname[j]));
                    //生成一个记录
                    proreplace(Convert.ToString(Gstrname[j]));
                    //删除不需要的行
                    delsingle(Convert.ToString(Gstrname[j]));
                }                
            }
            //生成一个配置表
            gconfig(); 
            Gcount = 0;
            MessageBox.Show("OK");
            ProStatus.Text = "处理完成";
            return true;
        }


        public void gconfig() 
        {
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            int BomNum = 0, CopyBom = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "多表配置样板")
                {
                    BomNum = i;
                }
                if (workbook.Worksheets[i].Name == "多表配置")
                {
                    CopyBom = i;
                }
            }

            //更改上一版本为副本
            if (CopyBom != 0)
            {
                Excel.Worksheet CopyBomSheet = workbook.Worksheets[CopyBom];//要操作的表的索引。
                CopyBomSheet.Name = CopyBomSheet.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
            }

            //PCB输出样板存副本
            Excel.Worksheet BomConfigSheetCopy = workbook.Worksheets[BomNum];//要操作的表的索引。
            //复制一个表
            object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            BomConfigSheetCopy.Copy(Missing, BomConfigSheetCopy);
            //对新建的PCB输出样板进行操作
            Excel.Worksheet BomConfigSheet = workbook.Worksheets[BomNum + 1];//要操作的表的索引。
            BomConfigSheet.Name = "多表配置";
           // ProStatus.Text = "正在处理" + BomConfigSheet.Name + "表，请稍后...";

            for (int i = 0; i < Gcount; i++)
            {                
                //获取文件名
                  //获取文件扩展名
                comboBoxSoftRev.Text = "ad10";
                BomConfigSheet.Cells[i + 2, 1] = i + 1;         //序号
                BomConfigSheet.Cells[i + 2, 2] = "L1305(样板)";       //项目名称
                BomConfigSheet.Cells[i + 2, 3] = DateTime.Now.ToString("yyyy-MM-dd");       //打印日期
                //获取BOM文件名 3列
                BomConfigSheet.Cells[i + 2, 4] = Gstrname[i]; // TempPath.Substring(TempPath.LastIndexOf("\\") + 1, TempPath.LastIndexOf(".") - (TempPath.LastIndexOf("\\") + 1));
                BomConfigSheet.Cells[i + 2, 5] = "机车信号主机板(样板)";     //中文名
                BomConfigSheet.Cells[i + 2, 6] = Gstrname[i];    //PCB板名
                BomConfigSheet.Cells[i + 2, 7] = "V10(样板)";     //PCB版本
                BomConfigSheet.Cells[i + 2, 8] = "150*100";     //PCB尺寸
                BomConfigSheet.Cells[i + 2, 9] = DateTime.Now.ToString("yyyy-MM-dd");   //PCB板内日期
                BomConfigSheet.Cells[i + 2, 10] = "2";     //板层
                BomConfigSheet.Cells[i + 2, 11] = "10";     //下单数量
                BomConfigSheet.Cells[i + 2, 12] = "1.6";     //厚度
                BomConfigSheet.Cells[i + 2, 13] = "无铅喷锡";     //加工工艺
                BomConfigSheet.Cells[i + 2, 14] = DateTime.Now.ToString("yyyy-MM-dd");    //加工日期
                BomConfigSheet.Cells[i + 2, 15] = "目录及文件名 路径 ";                 //目录及文件名 路径 
                BomConfigSheet.Cells[i + 2, 16] = comboBoxSoftRev.Text;                   //软件版本
            }
            //防止没有文件乱执行
            // 合并总表功能有作用
            // button4.Enabled = true;  
            //保存配置有用了
            button22.Enabled = true;
        }

        //tSingleList.Add(tempstr);
        //for (int tcol = 2; tcol < 10; tcol++)
        //{                                
        //    range = SingleBomSheet.Range[SingleBomSheet.Cells[trows, tcol], SingleBomSheet.Cells[trows, tcol]];
        //    tempstr = range.Text.ToString();
        //    if (tempstr !="")
        //    {
        //        tSingleList.Add(tempstr);
        //    }
        //    else
        //    {
        //        tSingleList.Add("nc删除");
        //    }


        ////重组写入
        //string AllStr = "";
        //for (int i = 0; i < Lib_List.Count; i++)
        //{
        //    AllStr = AllStr + Lib_List[i].Replace("\n", "");
        //     AllStr += Environment.NewLine;//字符串换行
        //}
        ////写入
        //StreamWriter SWriter = new StreamWriter(@"E:\AllLib.txt", false, Encoding.Default);//实例化写入流对象
        //SWriter.Write(AllStr);//先文本文件中写入内容
        //SWriter.Close();//关闭写入流对象
        //SWriter.Dispose();//释放写入流所占用的资源

        ////------------------------单表一个一个的生成-----------------------------------------
        //for (int i = 0; i < ConfigList.Count; )
        //{
        //    //----------读取当前单表内容到SingleBomList列表中--------------------------------
        //    //读取分表内容到SingleBomList中去
        //    ReadSingleBomToList(ConfigList[i + 3]);
        //    //----------读取当前单表内容到SingleBomList列表中结束----------------------------
        //    int sheetnum = 0;
        //    for (int s = 0; s < DelBom.Length; s++)
        //    {
        //        for (int j = 1; j <= OutWorkBook.Worksheets.Count; j++)
        //        {
        //            if (OutWorkBook.Worksheets[j].Name == "料单样板")
        //            {
        //                sheetnum = j;
        //            }
        //        }
        //    }

        //    SingleBomSheet = OutWorkBook.Worksheets[sheetnum];

        //    if (i + 16 < ConfigList.Count)
        //    {
        //        SingleBomSheet.Copy(Missing, SingleBomSheet);
        //        //料单样板
        //        SingleBomSheet = OutWorkBook.Worksheets[sheetnum + 1]; //要操作的表的索引。
        //    }

        //    //单表的名字
        //    SingleBomSheet.Name = ConfigList[i + 3];        // ComSheets.Text;              


        //    ProStatus.Text = "正在生成分表：" + ConfigList[i + 3] + "。请稍后。。。";


        private void button30_Click(object sender, EventArgs e)
        {
            if (OpenExcel())
            {
                button22.Enabled = false;
                button32.Enabled = true;
            }


            ///*处理两个工作表分别为：料单样板、器件库*/
            //Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            //int BomNum = 0, CopyBom = 0;
            //string[] tabname = new string[workbook.Worksheets.Count];   //存工作簿中所有表名
            //for (int i = 1; i <= workbook.Worksheets.Count; i++)
            //{
            //    tabname[i - 1] = workbook.Worksheets[i].Name;       //存工作簿
            //    if (workbook.Worksheets[i].Name == "多表配置样板")
            //    {
            //        BomNum = i;
            //    }
            //    if (workbook.Worksheets[i].Name == "多表配置")
            //    {
            //        CopyBom = i;
            //    }
            //}

            ////更改上一版本为副本
            //if (CopyBom != 0)
            //{
            //    Excel.Worksheet CopyBomSheet = workbook.Worksheets[CopyBom];//要操作的表的索引。
            //    CopyBomSheet.Name = CopyBomSheet.Name + "副本" + PcbOldCopyCount; PcbOldCopyCount++;
            //}

            ////PCB输出样板存副本
            //Excel.Worksheet BomConfigSheetCopy = workbook.Worksheets[BomNum];//要操作的表的索引。
            ////复制一个表
            //object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            //BomConfigSheetCopy.Copy(Missing, BomConfigSheetCopy);
            ////对新建的PCB输出样板进行操作
            //Excel.Worksheet BomConfigSheet = workbook.Worksheets[BomNum + 1];//要操作的表的索引。
            //BomConfigSheet.Name = "多表配置";
            ////ProStatus.Text = string.Empty; //清空内容
            //ProStatus.Text = "正在处理" + BomConfigSheet.Name + "表，请稍后...";

            ////存入打开文件个数
            //BomNumCount = openExcel.FileNames.Length;
            //for (int i = 0; i < openExcel.FileNames.Length; i++)
            //{
            //    BomFilePath[i] = openExcel.FileNames[i];             //目录及文件名 存到全局变量里
            //    TempPath = openExcel.FileNames[i];                   //目录及文件名
            //    ProStatus.Text = "已选择bom文件！等待输入参数进行转换。";   //显示状态                    
            //    //获取文件名
            //    TextBoxBomName.Text = TempPath.Substring(TempPath.LastIndexOf("\\") + 1, TempPath.LastIndexOf(".") - (TempPath.LastIndexOf("\\") + 1)); //获取文件名
            //    BomFileName[i] = TextBoxBomName.Text;//后缀 确认板本
            //    //获取文件扩展名
            //    if (TempPath.Substring(TempPath.LastIndexOf(".") + 1, TempPath.Length - TempPath.LastIndexOf(".") - 1) == "txt")//获取文件扩展名
            //    { comboBoxSoftRev.Text = "ad10"; }
            //    else
            //    { comboBoxSoftRev.Text = "protel99se"; }
            //    BomConfigSheet.Cells[i + 2, 1] = i + 1;         //序号
            //    BomConfigSheet.Cells[i + 2, 2] = "L1305";       //项目名称
            //    BomConfigSheet.Cells[i + 2, 3] = DateTime.Now.ToString("yyyy-MM-dd");       //打印日期
            //    //获取BOM文件名 3列
            //    BomConfigSheet.Cells[i + 2, 4] = TextBoxBomName.Text; // TempPath.Substring(TempPath.LastIndexOf("\\") + 1, TempPath.LastIndexOf(".") - (TempPath.LastIndexOf("\\") + 1));
            //    BomConfigSheet.Cells[i + 2, 5] = "机车信号主机板";     //中文名
            //    BomConfigSheet.Cells[i + 2, 6] = TextBoxBomName.Text;    //PCB板名
            //    BomConfigSheet.Cells[i + 2, 7] = "V10";     //PCB版本
            //    BomConfigSheet.Cells[i + 2, 8] = "150*100";     //PCB尺寸
            //    BomConfigSheet.Cells[i + 2, 9] = DateTime.Now.ToString("yyyy-MM-dd");   //PCB板内日期
            //    BomConfigSheet.Cells[i + 2, 10] = "2";     //板层
            //    BomConfigSheet.Cells[i + 2, 11] = "10";     //下单数量
            //    BomConfigSheet.Cells[i + 2, 12] = "1.6";     //厚度
            //    BomConfigSheet.Cells[i + 2, 13] = "无铅喷锡";     //加工工艺
            //    BomConfigSheet.Cells[i + 2, 14] = DateTime.Now.ToString("yyyy-MM-dd");    //加工日期
            //    BomConfigSheet.Cells[i + 2, 15] = openExcel.FileNames[i];                 //目录及文件名 路径 
            //    BomConfigSheet.Cells[i + 2, 16] = comboBoxSoftRev.Text;                   //软件版本
            //}
            ////防止没有文件乱执行
            //// 合并总表功能有作用
            //// button4.Enabled = true;  
            ////保存配置有用了
            //button22.Enabled = true;
        }

        private void button31_Click(object sender, EventArgs e)
        {
            CollectOut();




            //默认情况不输出
            buttonALLPCPOUT.Enabled = true;
            //整理的那个表示“成功”的按键
            buttonAdvancedStatus.Enabled = true;
            //整理按钮
            button7.Enabled = true;
            //多表合并重新可用
            //button4.Enabled = true;
            //辅助整理打开
            button11.Enabled = true;
            //辅助单表查找替换
            //button12.Enabled = true;
            //保存分表到数据库
            button24.Enabled = true;

            comboBox4.Items.Clear();
            comboBox4.Text = "总表";

            //现在查出问题了，下面这一行可以不用加了
            //把总表的所有内容存起来
            Addlist();
            //读取替换表内容
            ReaderReplaceList();
            //替换总表内容
            Replacebom("总表");

            //辅助执行一次，才方法二次整理料单
            //fuzhu();
            ProStatus.Text = "多表转换已完成。";
            //只有保存了配置并生成了表才能输出
            button8.Enabled = true;

            //总表封面
            AllbomCover();

            MessageBox.Show("总表合并完成！");
        }

        public void menfun()
        {
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿 
            Excel.Range range;
            int SortTemp = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "排序表")
                {
                    SortTemp = i;
                }

            }

            Excel.Worksheet SortSheet = workbook.Worksheets[SortTemp];//要操作的表的索引         

            //再排序

            //存储所有排序表内容到 GAllSortList 中去
            //List<string> GAllSortList = new List<string>();
            //bool GSortflag = false;

            SortSheet = workbook.Worksheets[SortTemp];

            GAllSortList.Clear();
            for (int q = 2; q < 200000; q++)
            {
                range = SortSheet.Range[SortSheet.Cells[q, 1], SortSheet.Cells[q, 1]];
                if (range.Text.ToString() != "")
                {
                    range = SortSheet.Range[SortSheet.Cells[q, 2], SortSheet.Cells[q, 2]];
                    GAllSortList.Add(range.Text.ToString());
                    range = SortSheet.Range[SortSheet.Cells[q, 3], SortSheet.Cells[q, 3]];
                    GAllSortList.Add(range.Text.ToString());
                }
                else
                {
                    break;
                }
            }


            //重组写入
            string AllStr = "";
            for (int i = 0; i < GAllSortList.Count; i++)
            {
                AllStr = AllStr + GAllSortList[i];
                AllStr += Environment.NewLine;//字符串换行
            }
            //写入
            StreamWriter SWriter = new StreamWriter(@"E:\AllLib.txt", false, Encoding.Default);//实例化写入流对象
            SWriter.Write(AllStr);//先文本文件中写入内容
            SWriter.Close();//关闭写入流对象
            SWriter.Dispose();//释放写入流所占用的资源

        }

        public void sortfunv11()
        {
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿     
            Excel.Range range;
            int allbom = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "总表")
                {
                    allbom = i;
                }
            }
            Excel.Worksheet AllBomSheet = workbook.Worksheets[allbom];//要操作的表的索引 
            //暂存总表内容
            List<string> TempList = new List<string>();
            string stemp; //int id00 = 1;
            for (int p = 5; p < 200000; p++)
            {
                range = AllBomSheet.Range[AllBomSheet.Cells[p, 1], AllBomSheet.Cells[p, 1]];
                stemp = range.Text.ToString();
                if (stemp != "")
                {
                    //TempList.Add(id00.ToString()); id00++;
                    TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 2], AllBomSheet.Cells[p, 2]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 3], AllBomSheet.Cells[p, 3]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 4], AllBomSheet.Cells[p, 4]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                }
                else
                {
                    break;
                }
            }

            //开始排序
            List<string> TempList2 = new List<string>();
            //string[] tempint = new string[TempList.Count / 4];
            //int tempints = 0;
            for (int ai = 0; ai < GAllSortList.Count; )
            {
                for (int jj = 0; jj < TempList.Count; )
                {
                    if (GAllSortList[ai] == TempList[jj + 1])
                    {
                        //tempint[tempints] = TempList[jj + 0]; 
                        //tempints++;
                        TempList2.Add(TempList[jj + 0]);
                        TempList2.Add(GAllSortList[ai + 1]);TempList[jj + 1]=GAllSortList[ai + 1];
                        TempList2.Add(TempList[jj + 2]);
                        TempList2.Add(TempList[jj + 3]);
                    }
                    jj = jj + 4;
                }
                ai = ai + 2; ;
            }

            //重新填入
            int ttmp = 0, lentht = TempList2.Count / 4 + 5;
            for (int lls = 5; lls < lentht; lls++)
            {
                AllBomSheet.Cells[lls, 1] = TempList2[ttmp * 4 + 0];
                AllBomSheet.Cells[lls, 2] = TempList2[ttmp * 4 + 1];
                AllBomSheet.Cells[lls, 3] = TempList2[ttmp * 4 + 2];
                AllBomSheet.Cells[lls, 4] = TempList2[ttmp * 4 + 3];
                ttmp++;
            }

            int ttid = lentht, idd2f = 0;
            for (int inbom = 0; inbom < TempList.Count; )
            {
                for (int d = 0; d < TempList2.Count; )
                {
                    if (TempList[inbom + 1] == TempList2[d + 1])
                    {
                        idd2f = 1;
                        break;
                    }
                    d = d + 4;
                }
                if (idd2f != 1)
                {
                    idd2f = 0;
                    AllBomSheet.Cells[ttid, 1] = TempList[inbom + 0];
                    AllBomSheet.Cells[ttid, 2] = TempList[inbom + 1];
                    AllBomSheet.Cells[ttid, 3] = TempList[inbom + 2];
                    AllBomSheet.Cells[ttid, 4] = TempList[inbom + 3];
                    ttid++;
                }
                else
                {
                    idd2f = 0;
                }
                inbom = inbom + 4;
            }

        }


        //汇总表输出
        public void CollectOut()
        {
            // .Text = "正在生成总表，请稍后。";
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿     
            Excel.Range range;

            int TempExcelRow = 5, IDnum = 1; //第5行开始

            //存内容到全局变量上         

            //把所有分表的内容统一汇总到 All_List 列表中
            Excel.Worksheet BomConfigSheet;

            OkAllList.Clear();

            for (int table = 0; table < BomNumCount; table++)
            {
                for (int i = 1; i <= workbook.Worksheets.Count; i++)
                {
                    if (workbook.Worksheets[i].Name == BomFileName[table])
                    {
                        // BomNum = i;
                        BomConfigSheet = workbook.Worksheets[i];//要操作的表的索引。
                        //存储字符的个数
                        string TempStr = "", TempStr1 = "", TempStr2 = "", TempStr3 = ""; int flag = 0;                                                                                                        //存储读取的内容
                        //把所有单表的器件写入All_List进行统一处理
                        int tid = 0;
                        for (int TempRow = 3; TempRow < 20000; TempRow++)//遍历数据集中表的行数
                        {
                            //读取第3行第一列为序号
                            range = BomConfigSheet.Range[BomConfigSheet.Cells[TempRow, 1], BomConfigSheet.Cells[TempRow, 1]];                         //第1列内容为序号
                            tid = TempRow - 2;
                            if (range.Text.ToString() != "")
                            {
                                range = BomConfigSheet.Range[BomConfigSheet.Cells[TempRow, 3], BomConfigSheet.Cells[TempRow, 3]];   //第3-5列内容为器件名称，规格型号，封装
                                TempStr1 = range.Text.ToString();                                
                                range = BomConfigSheet.Range[BomConfigSheet.Cells[TempRow, 4], BomConfigSheet.Cells[TempRow, 4]];   //第3-5列内容为器件名称，规格型号，封装
                                TempStr2 = range.Text.ToString();                                
                                range = BomConfigSheet.Range[BomConfigSheet.Cells[TempRow, 5], BomConfigSheet.Cells[TempRow, 5]];   //第3-5列内容为器件名称，规格型号，封装
                                TempStr3 = range.Text.ToString();
                                if (IDnum > 1)
                                {
                                    //查重再存入
                                    for (int j = 0; j < OkAllList.Count ; )
                                    {
                                        if ((TempStr1==OkAllList[j+1] ) && (TempStr2==OkAllList[j+2] ) &&(TempStr3==OkAllList[j+3]) )
                                        {
                                            flag = 1;
                                            break;
                                        }
                                        j = j + 4;
                                    }

                                    if (flag == 1)
                                    {
                                        flag = 0;
                                    }
                                    else
                                    {
                                        OkAllList.Add(IDnum.ToString());
                                        OkAllList.Add(TempStr1);
                                        OkAllList.Add(TempStr2);
                                        OkAllList.Add(TempStr3);
                                        flag = 0;
                                        TempExcelRow++; IDnum++;
                                    }
                                    
                                }
                                else
                                {
                                    OkAllList.Add(IDnum.ToString());
                                    OkAllList.Add(TempStr1);
                                    OkAllList.Add(TempStr2);
                                    OkAllList.Add(TempStr3);
                                    TempExcelRow++; IDnum++;
                                }                               

                            }
                            else
                            {
                                break;
                            }
                        }
                    }//处理单表添加
                } //查表FOR                   
            } //表处理完成
            ////MessageBox.Show("多表处理完成！");


            Excel.Worksheet AllBomSheet;
            Excel.Worksheet SortSheet;
            int AllBom = 0, SortTemp = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == "总表样板")
                {
                    AllBom = i;
                }
                if (workbook.Worksheets[i].Name == "总表")
                {                    
                    AllBomSheet = workbook.Worksheets[i];//要操作的表的索引 
                    AllBomSheet.Name = "总表副本" + PcbOldCopyCount; PcbOldCopyCount++;
                }

            }
            AllBomSheet = workbook.Worksheets[AllBom];//要操作的表的索引            
            object Missing = System.Reflection.Missing.Value;//获取缺少的object类型值
            AllBomSheet.Copy(Missing, AllBomSheet);
            //对新建的PCB输出样板进行操作
            AllBomSheet = workbook.Worksheets[AllBom + 1];//要操作的表的索引。
            AllBomSheet.Name = "总表";


            //-----------------根据分表数量进行列宽分配------------------------------------------
            //更改列宽，重新分配打开多个表的列宽
            //StartColumn 开始列为5，
            //EndColumn = 结束列为5  + BomNumCount + 6 
            //TabNum = 表的结束列 BomNumCount + 6;
            int DelTab, addcol;// = 22 - BomNumCount; 
            int StartColumn = 5, EndColumn = BomNumCount + 6 + 5, TabNum = BomNumCount + 6;
            double TabWidth = (119 / (BomNumCount + 6)) + 0.6;
            if (TabWidth < 1)
            {
                TabWidth = 1;
            }

            if (BomNumCount < 23)
            {
                DelTab = 22 - BomNumCount;
                while (DelTab != 0)
                {
                    range = AllBomSheet.Columns["G:G", System.Type.Missing];
                    range.Columns.Delete();
                    DelTab--;
                }
            }
            else
            {
                addcol = BomNumCount - 22;
                while (addcol != 0)
                {
                    range = AllBomSheet.Columns["G:G", System.Type.Missing];
                    range.Insert(Excel.XlDirection.xlDown, missing);
                    addcol--;
                }
            }

            while (StartColumn != EndColumn)
            {
                range = AllBomSheet.Columns[GetColumnName(StartColumn) + ":" + GetColumnName(StartColumn), System.Type.Missing];
                range.ColumnWidth = TabWidth;
                StartColumn++;
            }
            //-----------------根据分表数量进行列宽分配------------------------------------------

            //表名的表头
            for (int i = 0; i < BomNumCount; i++)
            {
                AllBomSheet.Cells[1, 7 + i] = BomFileName[i];
                AllBomSheet.Cells[4, 7 + i] = BomFileName[i];

                AllBomSheet.Cells[2, 7 + i] = 10; //下单数量
                AllBomSheet.Cells[3, 7 + i] = 10; //下单数量
            }

            TempExcelRow = 5; 
            IDnum = 1; //第5行开始

            //写入所有行
            int count = (OkAllList.Count / 4) + 5;
            for (int i = 5; i < count; i++)
            {
                AllBomSheet.Cells[TempExcelRow, 1] = OkAllList[((i - 5) * 4) + 0];
                AllBomSheet.Cells[TempExcelRow, 2] = OkAllList[((i - 5) * 4) + 1];
                AllBomSheet.Cells[TempExcelRow, 3] = OkAllList[((i - 5) * 4) + 2];
                AllBomSheet.Cells[TempExcelRow, 4] = OkAllList[((i - 5) * 4) + 3];

                string K1 = "", K2 = "=", K4 = "=";
                //表名的表头对应的值
                for (int f = 0; f < BomNumCount; f++)
                {
                    AllBomSheet.Cells[TempExcelRow, 7 + f] = @"=SUMIFS(" + BomFileName[f] + "!F:F," + BomFileName[f] + "!D:D,总表!C" + TempExcelRow + "," + BomFileName[f] + "!E:E,总表!D" + TempExcelRow + ")";
                }

                K1 = ""; K2 = "="; K4 = "=";
                for (int k = 7; k < 7 + BomNumCount; k++)
                {
                    K1 = GetColumnName(k);
                    if (k == (7 + BomNumCount - 1))
                    {
                        K2 = K2 + K1 + "$2*" + K1 + TempExcelRow;
                        K4 = K4 + K1 + "$3*" + K1 + TempExcelRow;
                    }
                    else
                    {
                        K2 = K2 + K1 + "$2*" + K1 + TempExcelRow + "+";
                        K4 = K4 + K1 + "$3*" + K1 + TempExcelRow + "+";
                    }
                }
                AllBomSheet.Cells[TempExcelRow, 7 + BomNumCount] = @K2;
                AllBomSheet.Cells[TempExcelRow, 7 + BomNumCount + 1] = @K4;
                TempExcelRow++; IDnum++;
            }

            //进行排一下序AllSheet.Cells[i, 10 + BomNumCount]
            range = AllBomSheet.Range[AllBomSheet.Cells[5, 1], AllBomSheet.Cells[count - 1, 4]];//10 + BomNumCount + 1]
            //按3列升序排序
            range.Sort(
             range.Columns[2, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[4, missing], missing, Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             range.Columns[3, missing], Microsoft.Office.Interop.Excel.XlSortOrder.xlAscending,
             Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing, missing,
             Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortColumns,
             Microsoft.Office.Interop.Excel.XlSortMethod.xlPinYin,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal,
             Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal);


            menfun();
            sortfunv11();

            //重新生成一个新排列序号
            int ids = 1;
            for (int k = 5; k < 20000; k++)
            {
                range = AllBomSheet.Range[AllBomSheet.Cells[k, 1], AllBomSheet.Cells[k, 1]];
                if (range.Text.ToString() != "")
                {
                    AllBomSheet.Cells[k, 1] = Convert.ToString(ids); ids++;
                }
                else
                {
                    break;
                }
            }

            //自定义页眉
            AllBomSheet.PageSetup.LeftHeader = @"&""微软雅黑,常规""文件编号: QR/JS-7.3-13";
            AllBomSheet.PageSetup.CenterHeader = @"&""微软雅黑,常规""&18" + textBoxAllTitle.Text + "汇总表";
            AllBomSheet.PageSetup.RightHeader = @"&""微软雅黑,常规""版本:" + textBoxAllRev;// textBoxAllRev.Text textBoxBomRev.Text;
            //自定义页脚
            AllBomSheet.PageSetup.LeftFooter = @"▲代表关键器件";
            AllBomSheet.PageSetup.CenterFooter = @"&""微软雅黑,常规""第&P页/共&N页";
            AllBomSheet.PageSetup.RightFooter = "";


            //给分表加索引
            int excelrow = 3;
            string TempStr5 = "";
            Excel.Worksheet SingleSheet;
            for (int s = 0; s < BomNumCount; s++)
            {

                for (int n = 1; n <= workbook.Worksheets.Count; n++)
                {
                    if (workbook.Worksheets[n].Name == BomFileName[s])
                    {
                        SingleSheet = workbook.Worksheets[n];//要操作的表的索引。
                        SingleSheet.Cells[2, 8] = "=总表!" + GetColumnName(7 + s) + "3";

                        while (true)
                        {
                            range = SingleSheet.Range[SingleSheet.Cells[excelrow, 1], SingleSheet.Cells[excelrow, 1]];
                            TempStr5 = range.Text.ToString();
                            if (TempStr5 != "")
                            {
                                SingleSheet.Cells[excelrow, 10] = @"=SUMIFS(总表!" + GetColumnName(7 + s) + ":" + GetColumnName(7 + s) + ",总表!C:C," + SingleSheet.Name + "!D" + excelrow + ",总表!D:D," + SingleSheet.Name + "!E" + excelrow;
                                SingleSheet.Cells[excelrow, 8] = "=H$2*F" + excelrow;
                                excelrow++;
                            }
                            else
                            {
                                excelrow = 3;
                                break;
                            }
                        }
                    }
                }
            }


        }

        private void button32_Click(object sender, EventArgs e)
        {
            //保存当前配表
            ConfigPro("多表");


            bool flag = false;
            //查找配置表内部重复
            for (int i = 0; i < ConfigList.Count; )
            {
                for (int k = 0; k < ConfigList.Count; )
                {
                    if ((i != k) && (ConfigList[i + 4] == ConfigList[k + 4]))
                    {
                        MessageBox.Show("有重复的中文板名，请修改后再保存。", "提示");
                        flag = true;
                        goto out1;
                        // break;                        
                    }

                    k = k + 16;
                }
                i = i + 16;
            }

        out1:
            if (flag)
            {
                MessageBox.Show("配置表保存   不  成功。");
                ProStatus.Text = "配置表保存   不  成功，请修改后再保存。";
            }
            else
            {
                //查找重复
                //DoubleKiller() //返回值等于1就是表有重复
                DoubleKiller();
                //多表合并使能
                //button4.Enabled = true;
                //旧表的多表合并使能
                button31.Enabled = true;
                MessageBox.Show("保存配置表成功。");
                ProStatus.Text = "处理完成。";
            }            
        }

        public bool openexcel()
        {
            string TempPath = "";
            OpenFileDialog openExcel = new OpenFileDialog();        //实例化打开对话框对象
            openExcel.Filter = "Excel文件|*.xlsx|Excel文件|*.xls";  //设置打开文件筛选器
            openExcel.Multiselect = false;                           //设置打开对话框中不能多选

            ProStatus.Text = "正在处理,请稍后...";
            if (openExcel.ShowDialog() != DialogResult.OK)
            {
                 return false;
            }

            return true;
        }

        //反回说明
        //9 为错误
        //1 为点
        //2 为数字
        //3 为R
        //4 为K
        //5 为M
        //6 为P
        //7 为N
        //8 为U
        
        public int substringpro( string strpro)
        {

            if (strpro==".")
            {
                return 1;
            }
            if (strpro =="0")
            {
                return 2;
            }
            if (strpro == "1")
            {
                return 2;
            }
            if (strpro == "2")
            {
                return 2;
            }
            if (strpro == "3")
            {
                return 2;
            }
            if (strpro == "4")
            {
                return 2;
            }
            if (strpro == "5")
            {
                return 2;
            }
            if (strpro == "6")
            {
                return 2;
            }
            if (strpro == "7")
            {
                return 2;
            }
            if (strpro == "8")
            {
                return 2;
            }
            if (strpro == "9")
            {
                return 2;
            }
            if (strpro == "0")
            {
                return 2;
            }
            if (strpro == "R" || strpro == "r")
            {
                return 3;
            }
            if (strpro == "K" || strpro == "k")
            {
                return 4;
            }
            if (strpro == "M" ||strpro == "m")
            {
                return 5;
            }
            if (strpro == "P" || strpro == "p")
            {
                return 6;
            }
            if (strpro == "N" || strpro == "n")
            {
                return 7;
            }
            if (strpro == "U" || strpro == "u" || strpro == "μ")
            {
                return 8;
            }
            return 9;
        }

        //总表电阻排序程序
        public void ressort( string tabname)
        {
            int trows=0;
            if (tabname =="总表")
            {
                trows = 5; 
            }
            else
            {
                trows = 3;
            }
            //要调整的数值
            int[] numbert = new int[200];
            int NumCount = 0;

            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿     
            Excel.Range range;
            int allbom = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == tabname)
                {
                    allbom = i;
                }
            }
            Excel.Worksheet AllBomSheet = workbook.Worksheets[allbom];//要操作的表的索引 

            /*
             暂存总表内容 到 TempList中，
             并记录总行数的最后一行数值班传给变量rows
            */
            List<string> TempList = new List<string>();
            string stemp; //int id00 = 1;
            int rows = 0;            
            for (int p = trows; p < 200000; p++)
            {
                range = AllBomSheet.Range[AllBomSheet.Cells[p, 1], AllBomSheet.Cells[p, 1]];
                stemp = range.Text.ToString();
                if (stemp != "")
                {
                    TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 2], AllBomSheet.Cells[p, 2]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 3], AllBomSheet.Cells[p, 3]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 4], AllBomSheet.Cells[p, 4]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                }
                else
                {
                    rows = p;
                    break;
                }
            }
            //***********************结束暂存总表内容*************************************8
            
            
            /**/
            //string stemp; 
            //int rows = 0;
            string partnames, parttypes, partfoots, partnamed, parttyped, partfootd;
            int tcount = 0, scount = 0, flag = 0, begin = trows;

            //存临时要排序的内容
            List<string> TSortList = new List<string>();

            do
            {
                flag = 0; tcount = 0; scount = 0;
                for (int m = begin; m < rows; m++)
                {

                    if (trows==5) //总表
                    {
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 2], AllBomSheet.Cells[m, 2]];
                        partnames = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 3], AllBomSheet.Cells[m, 3]];
                        parttypes = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 4], AllBomSheet.Cells[m, 4]];
                        partfoots = range.Text.ToString();

                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 2], AllBomSheet.Cells[m + 1, 2]];
                        partnamed = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 3], AllBomSheet.Cells[m + 1, 3]];
                        parttyped = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 4], AllBomSheet.Cells[m + 1, 4]];
                        partfootd = range.Text.ToString();
                    }
                    else//分表
                    {
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 3], AllBomSheet.Cells[m, 3]];
                        partnames = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 4], AllBomSheet.Cells[m, 4]];
                        parttypes = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 5], AllBomSheet.Cells[m, 5]];
                        partfoots = range.Text.ToString();

                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 3], AllBomSheet.Cells[m + 1, 3]];
                        partnamed = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 4], AllBomSheet.Cells[m + 1, 4]];
                        parttyped = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 5], AllBomSheet.Cells[m + 1, 5]];
                        partfootd = range.Text.ToString();
                    }

                    if ((stringcompare("电阻", partnames) == 2))
                    {
                        if (flag == 0)
                        {
                            scount = m;
                            flag = 1;
                        }
                        if ((partnames != partnamed) || (partfoots != partfootd))
                        {
                            tcount = m+1;
                            flag = 0;
                            break;
                        }
                    }
                }

                if ((tcount == 0) || (scount == 0))
                {
                    break;  //此板没有电阻 退出排序功能
                }

                //反回说明
                //0 为错误
                //1 为点
                //2 为数字
                //3 为R
                //4 为K
                //5 为M
                string TSTR = "";
                int DFLAG = 0, SFLAG = 0, RFLAG = 0, KFLAG = 0, MFLAG = 0,ReturnNUM = 0;
                if ((tcount != 0)) //不等于0就是有电阻的序列要排
                {
                    if (tcount - scount > 1)
                    {
                        for (int i = scount; i < tcount; i++)
                        {
                            

                            if (trows == 5) //总表
                            {
                                range = AllBomSheet.Range[AllBomSheet.Cells[i, 3], AllBomSheet.Cells[i, 3]];
                                TSTR = range.Text.ToString();
                            }
                            else//分表
                            {
                                range = AllBomSheet.Range[AllBomSheet.Cells[i, 4], AllBomSheet.Cells[i, 4]];
                                TSTR = range.Text.ToString();
                            }

                            for (int j = 0; j < TSTR.Length; j++)
                            {
                                ReturnNUM = substringpro(TSTR.Substring(j, 1));
                                if (ReturnNUM == 1) //判断点的位置
                                {
                                    DFLAG = j;
                                }
                                if (ReturnNUM == 3) //判断R的位置
                                {
                                    RFLAG = j;
                                    break;
                                }
                                if (ReturnNUM == 4) //判断K的位置
                                {
                                    KFLAG = j;
                                    break;
                                }
                                if (ReturnNUM == 5) //判断M的位置
                                {
                                    MFLAG = j;
                                    break;
                                }
                            }

                            int shuzi = 0, countt = 0, TEMPI = 0, CCOUNT = 0; string strt = "";
                            if (DFLAG != 0) //下面是带小数点的
                            {
                                if ((RFLAG != 0) || (KFLAG != 0) || (MFLAG != 0))
                                {   //这个是带小数点的数字 例如 5.2R,转换后变成5了。
                                    if ((RFLAG != 0))
                                    {
                                        DFLAG--; strt = "";
                                        while (DFLAG >= 0)
                                        { strt =  TSTR.Substring(DFLAG, 1) + strt ; DFLAG--; }

                                        numbert[NumCount] = (NumCount+1)/2; NumCount++;
                                        numbert[NumCount] = Convert.ToInt16(strt); NumCount++;
                                    }
                                    //这个是带小数点的数字 例如 5.2K,转换后变成5200了。
                                    if (KFLAG != 0)
                                    {
                                        DFLAG--; strt = "";
                                        while (DFLAG >= 0)
                                        { strt =  TSTR.Substring(DFLAG, 1)+strt; DFLAG--; }
                                        TEMPI = Convert.ToInt16(strt);
                                        KFLAG--; strt = "";
                                        while (KFLAG >= 0)
                                        {
                                            if (substringpro(TSTR.Substring(KFLAG, 1)) != 1)
                                            {
                                                strt = TSTR.Substring(KFLAG, 1) + strt; KFLAG--; CCOUNT++;
                                            }
                                            else
                                            {
                                                if (CCOUNT == 1)
                                                {
                                                    numbert[NumCount] = (NumCount + 1) / 2; NumCount++;
                                                    numbert[NumCount] = (Convert.ToInt16(strt) * 100) + TEMPI*1000; NumCount++;
                                                }
                                                if (CCOUNT == 2)
                                                {
                                                    numbert[NumCount] = (NumCount + 1) / 2; NumCount++;
                                                    numbert[NumCount] = (Convert.ToInt16(strt) * 10) + TEMPI*1000; NumCount++;
                                                }
                                                CCOUNT = 0;
                                                break;
                                            }
                                        }
                                    }

                                    //这个是带小数点的数字 例如 5.2M,转换后变成5200000了。
                                    if (MFLAG != 0)
                                    {
                                        DFLAG--; strt = "";
                                        while (DFLAG >= 0)
                                        { strt = TSTR.Substring(DFLAG, 1)+strt ; DFLAG--; }
                                        TEMPI = Convert.ToInt16(strt);
                                        MFLAG--;
                                        while (MFLAG >= 0)
                                        {
                                            if (substringpro(TSTR.Substring(MFLAG, 1)) != 1)
                                            {
                                                strt =  TSTR.Substring(MFLAG, 1) + strt ; MFLAG--; CCOUNT++;
                                            }
                                            else
                                            {
                                                if (CCOUNT == 1)
                                                {
                                                    numbert[NumCount] = (NumCount + 1) / 2; NumCount++;
                                                    numbert[NumCount] = (Convert.ToInt16(strt) * 100000) + TEMPI * 1000000; NumCount++;
                                                }
                                                if (CCOUNT == 2)
                                                {
                                                    numbert[NumCount] = (NumCount + 1) / 2; NumCount++;
                                                    numbert[NumCount] = (Convert.ToInt16(strt) * 10000) + TEMPI * 1000000; NumCount++;
                                                }
                                                CCOUNT = 0;
                                                break;
                                            }
                                        }
                                    }
                                }
                                else//这个是带小数点的数字 例如 5.2 没有R,转换后变成5了。
                                {
                                     for (int j = 0; j < TSTR.Length; j++)
                                    {
                                        if (substringpro(TSTR.Substring(j, 1)) != 2) //判断是否为数字
                                        {
                                            countt = j - 1;
                                            while (countt >= 0)
                                            {
                                                strt = TSTR.Substring(countt, 1) + strt; countt--;
                                            }
                                            numbert[NumCount] = (NumCount + 1) / 2; NumCount++;
                                            numbert[NumCount] = Convert.ToInt16(strt); NumCount++;
                                            break;
                                        }
                                    }                                
                                }
                            }
                            else
                            {//--------------------------转换没点，单数字或加R K M 开始------------------                                 
                                for (int j = 0; j < TSTR.Length; j++)
                                {
                                    if (substringpro(TSTR.Substring(j, 1)) != 2) //判断是否为数字
                                    {  //全数字 + R 或 K 或 M
                                        countt = j - 1;
                                        if (substringpro(TSTR.Substring(j, 1)) == 3)//R
                                        {
                                            while (countt >= 0)
                                            {
                                                strt = TSTR.Substring(countt, 1) + strt ; countt--;
                                            }
                                            numbert[NumCount] = (NumCount + 1) / 2; NumCount++;
                                            numbert[NumCount] = Convert.ToInt16(strt); NumCount++;
                                        }
                                        if (substringpro(TSTR.Substring(j, 1)) == 4)//K
                                        {
                                            while (countt >= 0)
                                            {
                                                strt = TSTR.Substring(countt, 1) + strt; countt--;
                                            }
                                            numbert[NumCount] = (NumCount + 1) / 2; NumCount++;
                                            numbert[NumCount] = Convert.ToInt16(strt) * 1000; NumCount++;
                                        }
                                        if (substringpro(TSTR.Substring(j, 1)) == 5)//M
                                        {
                                            while (countt >= 0)
                                            {
                                                strt = TSTR.Substring(countt, 1) + strt ; countt--;
                                            }
                                            numbert[NumCount] = (NumCount + 1) / 2; NumCount++;
                                            numbert[NumCount] = Convert.ToInt16(strt) * 1000000; NumCount++;
                                        }

                                        // 即不是R,也不是K,和M.
                                        if ((substringpro(TSTR.Substring(j, 1)) != 5) && (substringpro(TSTR.Substring(j, 1)) != 4) && (substringpro(TSTR.Substring(j, 1)) != 3)  )
                                        {

                                        
                                        }
                                        else
                                        {
                                            shuzi = 1;

                                        }
                                    
                                        break;
                                    }
                                }
                                if (shuzi != 1) //全数字
                                {
                                    for (int j = 0; j < TSTR.Length; j++)
                                    {
                                        if (substringpro(TSTR.Substring(j, 1)) != 2) //判断是否为数字
                                        {
                                            countt = j - 1;
                                            while (countt >= 0)
                                            {
                                                strt = TSTR.Substring(countt, 1) + strt; countt--;
                                            }
                                            numbert[NumCount] = (NumCount + 1) / 2; NumCount++;
                                            numbert[NumCount] = Convert.ToInt16(strt); NumCount++;
                                            break;
                                        }
                                    }                                
                                }

                            }//--------------------------转换单数字没点及带R,K,M结束------------------
                            DFLAG = 0; SFLAG = 0; RFLAG = 0; KFLAG = 0; MFLAG = 0;
                        }//for (int i = scount; i < tcount; i++) 电阻所有行内容

                        //加入处理方法，并重新填入                         
                        //处理电阻排序方
                        int temp;
                        for (int j = 0; j < (tcount-scount)*2; )
                        {
                            for (int i = 0; i <  (tcount-scount-1)*2; )
                            {
                                if (numbert[i+1] > numbert[i + 3])//数组元素大小按升序排列
                                {
                                    temp = numbert[i];
                                    numbert[i] = numbert[i + 2 ];
                                    numbert[i + 2] = temp;

                                    temp = numbert[i+1];
                                    numbert[i+1] = numbert[i + 3];
                                    numbert[i + 3] = temp;
                                }
                                i = i + 2;
                            }
                            j = j + 2;
                        }
                        //处理完成后再到回去处理剩下的电阻的排序


                        TSortList.Clear();

                        if (trows == 5) //总表
                        {
                            for (int i = scount; i < tcount; i++)
                            {
                                range = AllBomSheet.Range[AllBomSheet.Cells[(numbert[(i - scount) * 2] + scount), 3], AllBomSheet.Cells[(numbert[(i - scount) * 2] + scount), 3]];
                                TSortList.Add(range.Text.ToString());
                            }
                            for (int i = scount; i < tcount; i++)
                            {
                                AllBomSheet.Cells[i, 3] = TSortList[i - scount];
                            }
                    
                        }
                        else//分表
                        {
                            for (int i = scount; i < tcount; i++)
                            {
                                range = AllBomSheet.Range[AllBomSheet.Cells[i, 4], AllBomSheet.Cells[i, 4]];  //第四列为 器件参数值 即电阻值
                                TSortList.Add(range.Text.ToString());
                                range = AllBomSheet.Range[AllBomSheet.Cells[i, 6], AllBomSheet.Cells[i, 6]];  //6列为分表的器件数量
                                TSortList.Add(range.Text.ToString());
                                range = AllBomSheet.Range[AllBomSheet.Cells[i, 7], AllBomSheet.Cells[i, 7]]; // 第7列 数量指定的序号
                                TSortList.Add(range.Text.ToString());
                            }

                            for (int i = 0; i < tcount - scount; i++)
                            {
                                AllBomSheet.Cells[i + scount, 4] = TSortList[numbert[i * 2] * 3];
                                AllBomSheet.Cells[i + scount, 6] = TSortList[numbert[i * 2] * 3 + 1];
                                AllBomSheet.Cells[i + scount, 7] = TSortList[numbert[i * 2] * 3 + 2];
                            }

                        }



                        NumCount = 0;
                    
                        begin = tcount;
                        tcount = 0; scount = 0;
                    }
                    else
                    {
                        begin = tcount;
                    }//if (tcount-scount > 1) 大于1才有可比性 进行调整  //结束if (tcount-scount > 1) 只有一个电阻                    
                }
                else
                {
                    begin = rows;
                } //if ((tcount != 0))结束了，这张表上没有电阻
           } while (begin < rows-1);
        }





        //总表电容排序程序
        public void CapSort(string tabname)
        {
            int trows = 0;
            if (tabname == "总表")
            {
                trows = 5;
            }
            else
            {
                trows = 3;
            }
            //要调整的数值
            int[] numbert = new int[200];
            int NumCount = 0;

            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿     
            Excel.Range range;
            int allbom = 0;
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                if (workbook.Worksheets[i].Name == tabname)
                {
                    allbom = i;
                }
            }
            Excel.Worksheet AllBomSheet = workbook.Worksheets[allbom];//要操作的表的索引 

            /*
             暂存总表内容 到 TempList中，
             并记录总行数的最后一行数值班传给变量rows
            */
            List<string> TempList = new List<string>();
            string stemp; //int id00 = 1;
            int rows = 0;
            for (int p = trows; p < 200000; p++)
            {
                range = AllBomSheet.Range[AllBomSheet.Cells[p, 1], AllBomSheet.Cells[p, 1]];
                stemp = range.Text.ToString();
                if (stemp != "")
                {
                    TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 2], AllBomSheet.Cells[p, 2]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 3], AllBomSheet.Cells[p, 3]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                    range = AllBomSheet.Range[AllBomSheet.Cells[p, 4], AllBomSheet.Cells[p, 4]];
                    stemp = range.Text.ToString(); TempList.Add(stemp);
                }
                else
                {
                    rows = p;
                    break;
                }
            }
            //***********************结束暂存总表内容*************************************8


            /**/
            //string stemp; 
            //int rows = 0;
            string partnames, parttypes, partfoots, partnamed, parttyped, partfootd;
            int tcount = 0, scount = 0, flag = 0, begin = trows;

            //存临时要排序的内容
            List<string> TSortList = new List<string>();

            do
            {
                flag = 0; tcount = 0; scount = 0;
                for (int m = begin; m < rows; m++)
                {

                    if (trows == 5) //总表
                    {
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 2], AllBomSheet.Cells[m, 2]];
                        partnames = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 3], AllBomSheet.Cells[m, 3]];
                        parttypes = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 4], AllBomSheet.Cells[m, 4]];
                        partfoots = range.Text.ToString();

                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 2], AllBomSheet.Cells[m + 1, 2]];
                        partnamed = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 3], AllBomSheet.Cells[m + 1, 3]];
                        parttyped = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 4], AllBomSheet.Cells[m + 1, 4]];
                        partfootd = range.Text.ToString();
                    }
                    else//分表
                    {
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 3], AllBomSheet.Cells[m, 3]];
                        partnames = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 4], AllBomSheet.Cells[m, 4]];
                        parttypes = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m, 5], AllBomSheet.Cells[m, 5]];
                        partfoots = range.Text.ToString();

                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 3], AllBomSheet.Cells[m + 1, 3]];
                        partnamed = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 4], AllBomSheet.Cells[m + 1, 4]];
                        parttyped = range.Text.ToString();
                        range = AllBomSheet.Range[AllBomSheet.Cells[m + 1, 5], AllBomSheet.Cells[m + 1, 5]];
                        partfootd = range.Text.ToString();
                    }

                    if ((stringcompare("电容", partnames) == 2))
                    {
                        if (flag == 0)
                        {
                            scount = m;
                            flag = 1;
                        }
                        if ((partnames != partnamed) || (partfoots != partfootd))
                        {
                            tcount = m + 1;
                            flag = 0;
                            break;
                        }
                    }
                }

                if ((tcount == 0) || (scount == 0))
                {
                    break;  //此板没有电阻 退出排序功能
                }

                //反回说明
                
                //1 为点
                //2 为数字
                //3 为R
                //4 为K
                //5 为M
                //6 PF
                //7 NF
                //8 UF
                //9 错误
                string TSTR = "";

                string LStr = "", RStr = "";
                int LNum = 0, RNum = 0;

                int Lflag = 0,Rflag = 0,DFLAG = 0, SFLAG = 0, PFLAG = 0, NFLAG = 0, UFLAG = 0, ReturnNUM = 0;
                
                if ((tcount != 0)) //不等于0就是有电阻的序列要排
                {
                    if (tcount - scount > 1)
                    {
                        for (int i = scount; i < tcount; i++)
                        {


                            if (trows == 5) //总表
                            {
                                range = AllBomSheet.Range[AllBomSheet.Cells[i, 3], AllBomSheet.Cells[i, 3]];
                                TSTR = range.Text.ToString();
                            }
                            else//分表
                            {
                                range = AllBomSheet.Range[AllBomSheet.Cells[i, 4], AllBomSheet.Cells[i, 4]];
                                TSTR = range.Text.ToString();
                            }

                            //初始化
                            LStr = ""; RStr = "";
                            LNum = 0; RNum = 0;
                            Lflag = 0; Rflag = 0; DFLAG = 0; PFLAG = 0; NFLAG = 0; UFLAG = 0; ReturnNUM = 0;

                            for (int j = 0; j < TSTR.Length; j++)
                            {
                                ReturnNUM = substringpro(TSTR.Substring(j, 1));

                                if (ReturnNUM < 9 )
                                {
                                    //**************************************
                                    if (Lflag == 0)
                                    {
                                        if (ReturnNUM == 2) //数字
                                        {
                                            LStr = LStr + TSTR.Substring(j, 1);    
                                        }
                                        else
                                        {
                                            if (ReturnNUM == 1) //为点
                                            {
                                                DFLAG = j;     //为点 记录点的位置
                                                Lflag = 1;     //结束 左侧数字记录
                                            }
                                            else
                                            {
                                                if (ReturnNUM == 6) //判断P的位置
                                                {
                                                    PFLAG = j; break;                                                    
                                                }
                                                if (ReturnNUM == 7) //判断N的位置
                                                {
                                                    NFLAG = j; break; 
                                                }
                                                if (ReturnNUM == 8) //判断U的位置
                                                {
                                                    UFLAG = j; break; 
                                                }
                                            }
                                        }   
                                    }
                                    else
                                    {
                                        if (Rflag == 0) 
                                        {
                                            if (ReturnNUM == 2) //数字
                                            {
                                                RStr = RStr + TSTR.Substring(j, 1);
                                            }
                                            else
                                            {
                                                if (ReturnNUM == 6) //判断P的位置
                                                {
                                                    PFLAG = j; break;
                                                }
                                                if (ReturnNUM == 7) //判断N的位置
                                                {
                                                    NFLAG = j; break;
                                                }
                                                if (ReturnNUM == 8) //判断U的位置
                                                {
                                                    UFLAG = j; break;
                                                }                                               
                                            }                                           
                                        }
                                    }  
                                }
                                else
                                {
                                    break;
                                }     
                            }

                            //LStr = ""; RStr = "";
                            //LNum = 0; RNum = 0;
                            //Lflag = 0; Rflag = 0; DFLAG = 0; PFLAG = 0; NFLAG = 0; UFLAG = 0; ReturnNUM = 0;

                            if (PFLAG != 0)
                            {
                                    LNum = Convert.ToInt32(LStr);
                            }
                            else
                            {
                                if (NFLAG !=0)
                                {
                                    if (DFLAG != 0)
                                    {
                                        //you .  
                                        LNum = Convert.ToInt32(LStr) * 1000;

                                        if (RStr.Length==3)
                                        {
                                            RNum = Convert.ToInt32(RStr);       
                                        }
                                        else
                                        {
                                            if (RStr.Length == 2)
                                            {
                                                RNum = Convert.ToInt32(RStr) * 10;

                                            }
                                            else
                                            {
                                                if (RStr.Length == 1)
                                                {
                                                    RNum = Convert.ToInt32(RStr) * 100;
                                                }
                                            }
                                        }

                                        LNum = LNum + RNum;

                                    }
                                    else
                                    {
                                        LNum = Convert.ToInt32(LStr) * 1000;
                                        //no .
                                    }                                     
                                }
                                else
                                {
                                    if (UFLAG != 0)
                                    {
                                         if (DFLAG != 0)
                                         {
                                            //you .                                    
                                             //you .  
                                             LNum = Convert.ToInt32(LStr) * 1000000;

                                             if (RStr.Length == 3)
                                             {
                                                 RNum = Convert.ToInt32(RStr)*1000;
                                             }
                                             else
                                             {
                                                 if (RStr.Length == 2)
                                                 {
                                                     RNum = Convert.ToInt32(RStr) * 10000;
                                                 }
                                                 else
                                                 {
                                                     if (RStr.Length == 1)
                                                     {
                                                         RNum = Convert.ToInt32(RStr) * 100000;
                                                     }
                                                 }
                                             }

                                             LNum = LNum + RNum;
                                         }
                                         else
                                         {
                                           LNum = Convert.ToInt32(LStr)*1000000;
                                           //no .
                                        }   
                                    }
                                }
                            }

                            numbert[NumCount] = (NumCount + 1) / 2; NumCount++;
                            numbert[NumCount] = LNum; NumCount++;

                        }//for (int i = scount; i < tcount; i++) 电阻所有行内容

                        //加入处理方法，并重新填入                         
                        //处理电阻排序方
                        int temp;
                        for (int j = 0; j < (tcount - scount) * 2; )
                        {
                            for (int i = 0; i < (tcount - scount - 1) * 2; )
                            {
                                if (numbert[i + 1] > numbert[i + 3])//数组元素大小按升序排列
                                {
                                    temp = numbert[i];
                                    numbert[i] = numbert[i + 2];
                                    numbert[i + 2] = temp;

                                    temp = numbert[i + 1];
                                    numbert[i + 1] = numbert[i + 3];
                                    numbert[i + 3] = temp;
                                }
                                i = i + 2;
                            }
                            j = j + 2;
                        }
                        //处理完成后再到回去处理剩下的电阻的排序


                        TSortList.Clear();

                        if (trows == 5) //总表
                        {
                            for (int i = scount; i < tcount; i++)
                            {
                                range = AllBomSheet.Range[AllBomSheet.Cells[(numbert[(i - scount) * 2] + scount), 3], AllBomSheet.Cells[(numbert[(i - scount) * 2] + scount), 3]];
                                TSortList.Add(range.Text.ToString());
                            }
                            for (int i = scount; i < tcount; i++)
                            {
                                AllBomSheet.Cells[i, 3] = TSortList[i - scount];
                            }

                        }
                        else//分表
                        {
                            for (int i = scount; i < tcount; i++)
                            {
                                range = AllBomSheet.Range[AllBomSheet.Cells[i, 4], AllBomSheet.Cells[i, 4]];  //第四列为 器件参数值 即电阻值
                                TSortList.Add(range.Text.ToString());
                                range = AllBomSheet.Range[AllBomSheet.Cells[i, 6], AllBomSheet.Cells[i, 6]];  //6列为分表的器件数量
                                TSortList.Add(range.Text.ToString());
                                range = AllBomSheet.Range[AllBomSheet.Cells[i, 7], AllBomSheet.Cells[i, 7]]; // 第7列 数量指定的序号
                                TSortList.Add(range.Text.ToString());
                            }

                            for (int i = 0; i < tcount - scount; i++)
                            {
                                AllBomSheet.Cells[i + scount, 4] = TSortList[numbert[i * 2] * 3];
                                AllBomSheet.Cells[i + scount, 6] = TSortList[numbert[i * 2] * 3 + 1];
                                AllBomSheet.Cells[i + scount, 7] = TSortList[numbert[i * 2] * 3 + 2];
                            }

                        }

                        NumCount = 0;

                        begin = tcount;
                        tcount = 0; scount = 0;
                    }
                    else
                    {
                        begin = tcount;
                    }//if (tcount-scount > 1) 大于1才有可比性 进行调整  //结束if (tcount-scount > 1) 只有一个电阻                    
                }
                else
                {
                    begin = rows;
                } //if ((tcount != 0))结束了，这张表上没有电阻
            } while (begin < rows - 1);
        }     

        bool selectstor = false;
        private void comboBox5_MouseDown(object sender, MouseEventArgs e)
        { 
            /*处理两个工作表分别为：料单样板、器件库*/
            Excel.Workbook workbook = this.Application.Workbooks[1];    //工作簿
            comboBox5.Items.Clear();
            comboBox5.Text = "请选择要排序的表";
            for (int i = 1; i <= workbook.Worksheets.Count; i++)
            {
                comboBox5.Items.Add(workbook.Worksheets[i].Name);
            }
            selectstor = true;
        }

        //跟据选择的单个表，进行电阻电容自动排序
        private void RESSTORPRO_Click(object sender, EventArgs e)
        {
            if (selectstor)
            {
                ressort(comboBox5.Text);
                CapSort(comboBox5.Text);
                selectstor = false;
            }
            else
            {
                MessageBox.Show("请选择要排序的表");
            }
        }

        // 自动根据保存在配置表的所有表进行排序
        private void button33_Click(object sender, EventArgs e)
        {
            int tempint = ConfigList.Count;
            if (ConfigList.Count >= 16)
            {
                if (ConfigList.Count > 17)
                {
                    ressort("总表");
                    CapSort("总表");  
                }                               

                for (int i = 0; i < ConfigList.Count / 16; i++)
                {
                    ressort(ConfigList[i * 16 + 3]);
                    CapSort(ConfigList[i * 16 + 3]);
                }

                MessageBox.Show("排序完成。");
            }
            else
            {
                MessageBox.Show("没有找到时要排序的表");
            }
        }

     }
     
}
